
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_CN">
  <head>
    <meta charset="utf-8" />
    <title>socket --- 底层网络接口 &#8212; Python 3.7.8 文档</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <script type="text/javascript" src="../_static/translations.js"></script>
    
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="在 Python 3.7.8 文档 中搜索"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="关于这些文档" href="../about.html" />
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="copyright" title="版权所有" href="../copyright.html" />
    <link rel="next" title="ssl --- 套接字对象的TLS/SSL封装" href="ssl.html" />
    <link rel="prev" title="用 asyncio 开发" href="asyncio-dev.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/3/library/socket.html" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
    
    
    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
 

  </head><body>
  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="ssl.html" title="ssl --- 套接字对象的TLS/SSL封装"
             accesskey="N">下一页</a> |</li>
        <li class="right" >
          <a href="asyncio-dev.html" title="用 asyncio 开发"
             accesskey="P">上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" accesskey="U">网络和进程间通信</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-socket">
<span id="socket-low-level-networking-interface"></span><h1><a class="reference internal" href="#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> --- 底层网络接口<a class="headerlink" href="#module-socket" title="永久链接至标题">¶</a></h1>
<p><strong>源代码:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.7/Lib/socket.py">Lib/socket.py</a></p>
<hr class="docutils" />
<p>这个模块提供了访问BSD*套接字*的接口。在所有现代Unix系统、Windows、macOS和其他一些平台上可用。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>一些行为可能因平台不同而异，因为调用的是操作系统的套接字API。</p>
</div>
<p id="index-0">这个Python接口是用Python的面向对象风格对Unix系统调用和套接字库接口的直译：函数 <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a> 返回一个 <em class="dfn">套接字对象</em> ，其方法是对各种套接字系统调用的实现。形参类型一般与C接口相比更高级：例如在Python文件 <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> 和 <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> 操作中，接收操作的缓冲区分配是自动的，发送操作的缓冲区长度是隐式的。</p>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<dl class="simple">
<dt>模块 <a class="reference internal" href="socketserver.html#module-socketserver" title="socketserver: A framework for network servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socketserver</span></code></a></dt><dd><p>用于简化网络服务端编写的类。</p>
</dd>
<dt>模块 <a class="reference internal" href="ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a></dt><dd><p>套接字对象的TLS/SSL封装。</p>
</dd>
</dl>
</div>
<div class="section" id="socket-families">
<h2>套接字协议族<a class="headerlink" href="#socket-families" title="永久链接至标题">¶</a></h2>
<p>根据系统以及构建选项，此模块提供了各种 socket 协议簇。</p>
<p>特定的 socket 对象需要的地址格式将根据此 socket 对象被创建时指定的地址族被自动选择。socket 地址表示如下：</p>
<ul>
<li><p>一个绑定在文件系统节点上的 <a class="reference internal" href="#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a> 套接字的地址表示为一个字符串，使用文件系统字符编码和 <code class="docutils literal notranslate"><span class="pre">'surrogateescape'</span></code> 错误回调方法（see <span class="target" id="index-29"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0383"><strong>PEP 383</strong></a>）。一个地址在 Linux 的抽象命名空间被返回为带有初始的 null 字节的 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> ；注意在这个命名空间种的套接字可能与普通文件系统套接字通信，所以打算运行在 Linux 上的程序可能需要解决两种地址类型。当传递为参数时，一个字符串或字节类对象可以用于任一类型的地址。</p>
<blockquote>
<div><div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>以前，<a class="reference internal" href="#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a> 套接字路径被假设使用 UTF-8 编码。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>现在支持可写的 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">字节类对象</span></a>。</p>
</div>
</div></blockquote>
</li>
</ul>
<ul id="host-port">
<li><p>一对 <code class="docutils literal notranslate"><span class="pre">(host,</span> <span class="pre">port)</span></code> 被用于 <a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a> 地址族，<em>host</em> 是一个代表互联网域名表示法之内主机名或者一个 IPv4 地址的字符串，例如 <code class="docutils literal notranslate"><span class="pre">'daring.cwi.nl'</span></code> 或 <code class="docutils literal notranslate"><span class="pre">'100.50.200.5'</span></code>，<em>port</em> 是一个整数。</p>
<ul class="simple">
<li><p>对于 IPv4 地址，有两种可接受的特殊形式被用来代替一个主机地址： <code class="docutils literal notranslate"><span class="pre">''</span></code> 代表 <code class="xref py py-const docutils literal notranslate"><span class="pre">INADDR_ANY</span></code>，用来绑定到所有接口；字符串 <code class="docutils literal notranslate"><span class="pre">'&lt;broadcast&gt;'</span></code> 代表 <code class="xref py py-const docutils literal notranslate"><span class="pre">INADDR_BROADCAST</span></code>。此行为不兼容 IPv6，因此，如果你的 Python 程序打算支持 IPv6，则可能需要避开这些。</p></li>
</ul>
</li>
<li><p>对于 <a class="reference internal" href="#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET6</span></code></a> 地址族，使用一个四元组 <code class="docutils literal notranslate"><span class="pre">(host,</span> <span class="pre">port,</span> <span class="pre">flowinfo,</span> <span class="pre">scopeid)</span></code>， <em>flowinfo</em> 和 <em>scopeid</em> 代表了 C 库里 <code class="xref py py-const docutils literal notranslate"><span class="pre">struct</span> <span class="pre">sockaddr_in6</span></code> 中的 <code class="docutils literal notranslate"><span class="pre">sin6_flowinfo</span></code> 和 <code class="docutils literal notranslate"><span class="pre">sin6_scope_id</span></code> 成员。
对于 <a class="reference internal" href="#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> 模块中的方法， <em>flowinfo</em> 和 <em>scopeid</em> 可以被省略，只为了向后兼容。注意，<em>scopeid</em> 的省略可能会导致 IPv6 地址的操作范围问题。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>对于多播地址（其 <em>scopeid</em> 是有意义的），<em>地址</em> 可能不包含 <code class="docutils literal notranslate"><span class="pre">%scope``（或</span> <span class="pre">``zone</span> <span class="pre">id</span></code>）部分。该信息是多余的，可以放心省略（推荐）。</p>
</div>
</li>
<li><p><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_NETLINK</span></code> 套接字由一对 <code class="docutils literal notranslate"><span class="pre">(pid,</span> <span class="pre">groups)</span></code> 表示。</p></li>
<li><p>指定 <code class="xref py py-const docutils literal notranslate"><span class="pre">AF_TIPC</span></code> 地址族可以使用仅 Linux 支持的 TIPC 协议。TIPC 是一种开放的、非基于 IP 的网络协议，旨在用于集群计算环境。其地址用元组表示，其中的字段取决于地址类型。一般元组形式为 <code class="docutils literal notranslate"><span class="pre">(addr_type,</span> <span class="pre">v1,</span> <span class="pre">v2,</span> <span class="pre">v3</span> <span class="pre">[,</span> <span class="pre">scope])</span></code>，其中：</p>
<ul>
<li><p><em>addr_type</em> 取 <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_ADDR_NAMESEQ</span></code>、<code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_ADDR_NAME</span></code> 或 <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_ADDR_ID</span></code> 中的一个。</p></li>
<li><p><em>scope</em> 取 <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_ZONE_SCOPE</span></code>、<code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_CLUSTER_SCOPE</span></code> 和 <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_NODE_SCOPE</span></code> 中的一个。</p></li>
<li><p>如果 <em>addr_type</em> 为 <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_ADDR_NAME</span></code>，那么 <em>v1</em> 是服务器类型，<em>v2</em> 是端口标识符，<em>v3</em> 应为 0。</p>
<p>如果 <em>addr_type</em> 为 <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_ADDR_NAMESEQ</span></code>，那么 <em>v1</em> 是服务器类型，<em>v2</em> 是端口号下限，而 <em>v3</em> 是端口号上限。</p>
<p>如果 <em>addr_type</em> 为 <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_ADDR_ID</span></code>，那么 <em>v1</em> 是节点 (node)，<em>v2</em> 是 ref，<em>v3</em> 应为 0。</p>
</li>
</ul>
</li>
<li><p><a class="reference internal" href="#socket.AF_CAN" title="socket.AF_CAN"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_CAN</span></code></a> 地址族使用元组 <code class="docutils literal notranslate"><span class="pre">(interface,</span> <span class="pre">)</span></code>，其中 <em>interface</em> 是表示网络接口名称的字符串，如 <code class="docutils literal notranslate"><span class="pre">'can0'</span></code>。网络接口名 <code class="docutils literal notranslate"><span class="pre">''</span></code> 可以用于接收本族所有网络接口的数据包。</p>
<ul class="simple">
<li><p><a class="reference internal" href="#socket.CAN_ISOTP" title="socket.CAN_ISOTP"><code class="xref py py-const docutils literal notranslate"><span class="pre">CAN_ISOTP</span></code></a> 协议接受一个元组 <code class="docutils literal notranslate"><span class="pre">(interface,</span> <span class="pre">rx_addr,</span> <span class="pre">tx_addr)</span></code>，其中两个额外参数都是无符号长整数，都表示 CAN 标识符（标准或扩展标识符）。</p></li>
</ul>
</li>
<li><p><code class="xref py py-const docutils literal notranslate"><span class="pre">PF_SYSTEM</span></code> 协议簇的 <code class="xref py py-const docutils literal notranslate"><span class="pre">SYSPROTO_CONTROL</span></code> 协议接受一个字符串或元组 <code class="docutils literal notranslate"><span class="pre">(id,</span> <span class="pre">unit)</span></code>。其中字符串是内核控件的名称，该控件使用动态分配的 ID。而如果 ID 和内核控件的单元 (unit) 编号都已知，或使用了已注册的 ID，可以采用元组。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</li>
<li><p><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_BLUETOOTH</span></code> 支持以下协议和地址格式：</p>
<ul>
<li><p><code class="xref py py-const docutils literal notranslate"><span class="pre">BTPROTO_L2CAP</span></code> 接受 <code class="docutils literal notranslate"><span class="pre">(bdaddr,</span> <span class="pre">psm)</span></code>，其中 <code class="docutils literal notranslate"><span class="pre">bdaddr</span></code> 为字符串格式的蓝牙地址，<code class="docutils literal notranslate"><span class="pre">psm</span></code> 是一个整数。</p></li>
<li><p><code class="xref py py-const docutils literal notranslate"><span class="pre">BTPROTO_RFCOMM</span></code> 接受 <code class="docutils literal notranslate"><span class="pre">(bdaddr,</span> <span class="pre">channel)</span></code>，其中 <code class="docutils literal notranslate"><span class="pre">bdaddr</span></code> 为字符串格式的蓝牙地址，<code class="docutils literal notranslate"><span class="pre">channel</span></code> 是一个整数。</p></li>
<li><p><code class="xref py py-const docutils literal notranslate"><span class="pre">BTPROTO_HCI</span></code> 接受 <code class="docutils literal notranslate"><span class="pre">(device_id,)</span></code>，其中 <code class="docutils literal notranslate"><span class="pre">device_id</span></code> 为整数或字符串，它表示接口对应的蓝牙地址（具体取决于你的系统，NetBSD 和 DragonFlyBSD 需要蓝牙地址字符串，其他系统需要整数）。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span>添加 NetBSD 和 DragonFlyBSD 支持。</p>
</div>
</li>
<li><p><code class="xref py py-const docutils literal notranslate"><span class="pre">BTPROTO_SCO</span></code> 接受 <code class="docutils literal notranslate"><span class="pre">bdaddr</span></code>，其中 <code class="docutils literal notranslate"><span class="pre">bdaddr</span></code> 是 <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象，其中含有字符串格式的蓝牙地址（如 <code class="docutils literal notranslate"><span class="pre">b'12:23:34:45:56:67'</span></code> ），FreeBSD 不支持此协议。</p></li>
</ul>
</li>
<li><p><a class="reference internal" href="#socket.AF_ALG" title="socket.AF_ALG"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_ALG</span></code></a> 是一个仅 Linux 可用的、基于套接字的接口，用于连接内核加密算法。算法套接字可用包括 2 至 4 个元素的元组来配置 <code class="docutils literal notranslate"><span class="pre">(type,</span> <span class="pre">name</span> <span class="pre">[,</span> <span class="pre">feat</span> <span class="pre">[,</span> <span class="pre">mask]])</span></code>，其中：</p>
<ul class="simple">
<li><p><em>type</em> 是表示算法类型的字符串，如 <code class="docutils literal notranslate"><span class="pre">aead</span></code>、<code class="docutils literal notranslate"><span class="pre">hash</span></code>、<code class="docutils literal notranslate"><span class="pre">skcipher</span></code> 或 <code class="docutils literal notranslate"><span class="pre">rng</span></code>。</p></li>
<li><p><em>name</em> 是表示算法类型和操作模式的字符串，如 <code class="docutils literal notranslate"><span class="pre">sha256</span></code>、<code class="docutils literal notranslate"><span class="pre">hmac(sha256)</span></code>、<code class="docutils literal notranslate"><span class="pre">cbc(aes)</span></code> 或 <code class="docutils literal notranslate"><span class="pre">drbg_nopr_ctr_aes256</span></code>。</p></li>
<li><p><em>feat</em> 和 <em>mask</em> 是无符号 32 位整数。</p></li>
</ul>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: Linux 2.6.38, some algorithm types require more recent Kernels.</p>
<div class="versionadded">
<p><span class="versionmodified added">3.6 新版功能.</span></p>
</div>
</li>
<li><p><a class="reference internal" href="#socket.AF_VSOCK" title="socket.AF_VSOCK"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_VSOCK</span></code></a> 用于支持虚拟机与宿主机之间的通讯。该套接字用 <code class="docutils literal notranslate"><span class="pre">(CID,</span> <span class="pre">port)</span></code> 元组表示，其中 Context ID (CID) 和 port 都是整数。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: Linux &gt;= 4.8 QEMU &gt;= 2.8 ESX &gt;= 4.0 ESX Workstation &gt;= 6.5.</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</li>
<li><p><a class="reference internal" href="#socket.AF_PACKET" title="socket.AF_PACKET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_PACKET</span></code></a> 是一个底层接口，直接连接至网卡。数据包使用元组 <code class="docutils literal notranslate"><span class="pre">(ifname,</span> <span class="pre">proto[,</span> <span class="pre">pkttype[,</span> <span class="pre">hatype[,</span> <span class="pre">addr]]])</span></code> 表示，其中：</p>
<ul class="simple">
<li><p><em>ifname</em> - 指定设备名称的字符串。</p></li>
<li><p><em>proto</em> - 一个用网络字节序表示的整数，指定以太网协议版本号。</p></li>
<li><p><em>pkttype</em> - 指定数据包类型的整数（可选）：</p>
<ul>
<li><p><code class="docutils literal notranslate"><span class="pre">PACKET_HOST</span></code> （默认） - 数据包寻址到本地宿主机。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">PACKET_BROADCAST</span></code> - 物理层广播报文。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">PACKET_MULTIHOST</span></code> - 数据包发送到物理层多播地址。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">PACKET_OTHERHOST</span></code> - 被（处于混杂模式的）网卡驱动捕获的、发送到其他主机的数据包。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">PACKET_OUTGOING</span></code> - 来自本地主机的、回环到一个套接字的数据包。</p></li>
</ul>
</li>
<li><p><em>hatype</em> - 可选整数，指定 ARP 硬件地址类型。</p></li>
<li><p><em>addr</em> - 可选的类字节串对象，用于指定硬件物理地址，其解释取决于各设备。</p></li>
</ul>
</li>
</ul>
<p>如果你在 IPv4/v6 套接字地址的 <em>host</em> 部分中使用了一个主机名，此程序可能会表现不确定行为，因为 Python 使用 DNS 解析返回的第一个地址。套接字地址在实际的 IPv4/v6 中以不同方式解析，根据 DNS 解析和/或 host 配置。为了确定行为，在 <em>host</em> 部分中使用数字地址。</p>
<p>所有的错误都抛出异常。对于无效参数类型和内存溢出异常情况可能抛出普通异常；从 Python 3.3 开始，与套接字或地址语义有关的错误抛出 <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> 或它的子类之一（常用 <a class="reference internal" href="#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a>）。</p>
<p>可以用 <a class="reference internal" href="#socket.socket.setblocking" title="socket.socket.setblocking"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setblocking()</span></code></a> 设置非阻塞模式。一个基于超时的 generalization 通过 <a class="reference internal" href="#socket.socket.settimeout" title="socket.socket.settimeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">settimeout()</span></code></a> 支持。</p>
</div>
<div class="section" id="module-contents">
<h2>模块内容<a class="headerlink" href="#module-contents" title="永久链接至标题">¶</a></h2>
<p><a class="reference internal" href="#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> 模块导出以下元素。</p>
<div class="section" id="exceptions">
<h3>异常<a class="headerlink" href="#exceptions" title="永久链接至标题">¶</a></h3>
<dl class="exception">
<dt id="socket.error">
<em class="property">exception </em><code class="sig-prename descclassname">socket.</code><code class="sig-name descname">error</code><a class="headerlink" href="#socket.error" title="永久链接至目标">¶</a></dt>
<dd><p>一个被弃用的 <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> 的别名。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>根据 <span class="target" id="index-30"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3151"><strong>PEP 3151</strong></a>，这个类是 <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> 的别名。</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="socket.herror">
<em class="property">exception </em><code class="sig-prename descclassname">socket.</code><code class="sig-name descname">herror</code><a class="headerlink" href="#socket.herror" title="永久链接至目标">¶</a></dt>
<dd><p><a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> 的子类，本异常通常表示与地址相关的错误，比如那些在 POSIX C API 中使用了 <em>h_errno</em> 的函数，包括 <a class="reference internal" href="#socket.gethostbyname_ex" title="socket.gethostbyname_ex"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostbyname_ex()</span></code></a> 和 <a class="reference internal" href="#socket.gethostbyaddr" title="socket.gethostbyaddr"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostbyaddr()</span></code></a>。附带的值是一对 <code class="docutils literal notranslate"><span class="pre">(h_errno,</span> <span class="pre">string)</span></code>，代表库调用返回的错误。<em>h_errno</em> 是一个数字，而 <em>string</em> 表示 <em>h_errno</em> 的描述，它们由 C 函数 <code class="xref c c-func docutils literal notranslate"><span class="pre">hstrerror()</span></code> 返回。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>此类是 <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> 的子类。</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="socket.gaierror">
<em class="property">exception </em><code class="sig-prename descclassname">socket.</code><code class="sig-name descname">gaierror</code><a class="headerlink" href="#socket.gaierror" title="永久链接至目标">¶</a></dt>
<dd><p><a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> 的子类，本异常来自 <a class="reference internal" href="#socket.getaddrinfo" title="socket.getaddrinfo"><code class="xref py py-func docutils literal notranslate"><span class="pre">getaddrinfo()</span></code></a> 和 <a class="reference internal" href="#socket.getnameinfo" title="socket.getnameinfo"><code class="xref py py-func docutils literal notranslate"><span class="pre">getnameinfo()</span></code></a>，表示与地址相关的错误。附带的值是一对 <code class="docutils literal notranslate"><span class="pre">(error,</span> <span class="pre">string)</span></code>，代表库调用返回的错误。<em>string</em> 表示 <em>error</em> 的描述，它由 C 函数 <code class="xref c c-func docutils literal notranslate"><span class="pre">gai_strerror()</span></code> 返回。数字值 <em>error</em> 与本模块中定义的 <code class="xref py py-const docutils literal notranslate"><span class="pre">EAI_*</span></code> 常量之一匹配。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>此类是 <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> 的子类。</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="socket.timeout">
<em class="property">exception </em><code class="sig-prename descclassname">socket.</code><code class="sig-name descname">timeout</code><a class="headerlink" href="#socket.timeout" title="永久链接至目标">¶</a></dt>
<dd><p><a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> 的子类，当套接字发生超时，且事先已调用过 <a class="reference internal" href="#socket.socket.settimeout" title="socket.socket.settimeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">settimeout()</span></code></a> （或隐式地通过 <a class="reference internal" href="#socket.setdefaulttimeout" title="socket.setdefaulttimeout"><code class="xref py py-func docutils literal notranslate"><span class="pre">setdefaulttimeout()</span></code></a> ）启用了超时，则会抛出此异常。附带的值是一个字符串，其值总是 &quot;timed out&quot;。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>此类是 <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> 的子类。</p>
</div>
</dd></dl>

</div>
<div class="section" id="constants">
<h3>常量<a class="headerlink" href="#constants" title="永久链接至标题">¶</a></h3>
<blockquote>
<div><p>AF_* 和 SOCK_* 常量现在都在 <code class="xref py py-class docutils literal notranslate"><span class="pre">AddressFamily</span></code> 和 <code class="xref py py-class docutils literal notranslate"><span class="pre">SocketKind</span></code> 这两个 <a class="reference internal" href="enum.html#enum.IntEnum" title="enum.IntEnum"><code class="xref py py-class docutils literal notranslate"><span class="pre">IntEnum</span></code></a> 集合内。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.4 新版功能.</span></p>
</div>
</div></blockquote>
<dl class="data">
<dt id="socket.AF_UNIX">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">AF_UNIX</code><a class="headerlink" href="#socket.AF_UNIX" title="永久链接至目标">¶</a></dt>
<dt id="socket.AF_INET">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">AF_INET</code><a class="headerlink" href="#socket.AF_INET" title="永久链接至目标">¶</a></dt>
<dt id="socket.AF_INET6">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">AF_INET6</code><a class="headerlink" href="#socket.AF_INET6" title="永久链接至目标">¶</a></dt>
<dd><p>这些常量表示地址（和协议）簇，用于 <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a> 的第一个参数。如果 <a class="reference internal" href="#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a> 常量未定义，即表示不支持该协议。不同系统可能会有更多其他常量可用。</p>
</dd></dl>

<dl class="data">
<dt id="socket.SOCK_STREAM">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">SOCK_STREAM</code><a class="headerlink" href="#socket.SOCK_STREAM" title="永久链接至目标">¶</a></dt>
<dt id="socket.SOCK_DGRAM">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">SOCK_DGRAM</code><a class="headerlink" href="#socket.SOCK_DGRAM" title="永久链接至目标">¶</a></dt>
<dt id="socket.SOCK_RAW">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">SOCK_RAW</code><a class="headerlink" href="#socket.SOCK_RAW" title="永久链接至目标">¶</a></dt>
<dt id="socket.SOCK_RDM">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">SOCK_RDM</code><a class="headerlink" href="#socket.SOCK_RDM" title="永久链接至目标">¶</a></dt>
<dt id="socket.SOCK_SEQPACKET">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">SOCK_SEQPACKET</code><a class="headerlink" href="#socket.SOCK_SEQPACKET" title="永久链接至目标">¶</a></dt>
<dd><p>这些常量表示套接字类型，用于 <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a> 的第二个参数。不同系统可能会有更多其他常量可用。（一般只有 <a class="reference internal" href="#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a> 和 <a class="reference internal" href="#socket.SOCK_DGRAM" title="socket.SOCK_DGRAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_DGRAM</span></code></a> 可用）</p>
</dd></dl>

<dl class="data">
<dt id="socket.SOCK_CLOEXEC">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">SOCK_CLOEXEC</code><a class="headerlink" href="#socket.SOCK_CLOEXEC" title="永久链接至目标">¶</a></dt>
<dt id="socket.SOCK_NONBLOCK">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">SOCK_NONBLOCK</code><a class="headerlink" href="#socket.SOCK_NONBLOCK" title="永久链接至目标">¶</a></dt>
<dd><p>这两个常量（如果已定义）可以与上述套接字类型结合使用，并允许你设置一些原子性的 flags （从而避免可能的竞争条件和单独调用的需要）。</p>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p><a class="reference external" href="http://udrepper.livejournal.com/20407.html">Secure File Descriptor Handling （安全地处理文件描述符）</a> 提供了更详尽的解释。</p>
</div>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： Linux &gt;= 2.6.27。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt>
<code class="sig-name descname">SO_*</code></dt>
<dt id="socket.SOMAXCONN">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">SOMAXCONN</code><a class="headerlink" href="#socket.SOMAXCONN" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">MSG_*</code></dt>
<dt>
<code class="sig-name descname">SOL_*</code></dt>
<dt>
<code class="sig-name descname">SCM_*</code></dt>
<dt>
<code class="sig-name descname">IPPROTO_*</code></dt>
<dt>
<code class="sig-name descname">IPPORT_*</code></dt>
<dt>
<code class="sig-name descname">INADDR_*</code></dt>
<dt>
<code class="sig-name descname">IP_*</code></dt>
<dt>
<code class="sig-name descname">IPV6_*</code></dt>
<dt>
<code class="sig-name descname">EAI_*</code></dt>
<dt>
<code class="sig-name descname">AI_*</code></dt>
<dt>
<code class="sig-name descname">NI_*</code></dt>
<dt>
<code class="sig-name descname">TCP_*</code></dt>
<dd><p>此列表内的许多常量，记载在 Unix 文档中的套接字和/或 IP 协议部分，同时也定义在本 socket 模块中。它们通常用于套接字对象的 <code class="xref py py-meth docutils literal notranslate"><span class="pre">setsockopt()</span></code> 和 <code class="xref py py-meth docutils literal notranslate"><span class="pre">getsockopt()</span></code> 方法的参数中。在大多数情况下，仅那些在 Unix 头文件中有定义的符号会在本模块中定义，部分符号提供了默认值。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.6 版更改: </span>添加了 <code class="docutils literal notranslate"><span class="pre">SO_DOMAIN</span></code>、<code class="docutils literal notranslate"><span class="pre">SO_PROTOCOL</span></code>、<code class="docutils literal notranslate"><span class="pre">SO_PEERSEC</span></code>、<code class="docutils literal notranslate"><span class="pre">SO_PASSSEC</span></code>、<code class="docutils literal notranslate"><span class="pre">TCP_USER_TIMEOUT</span></code>、<code class="docutils literal notranslate"><span class="pre">TCP_CONGESTION</span></code>。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.6.5 版更改: </span>在 Windows 上，如果 Windows 运行时支持，则 <code class="docutils literal notranslate"><span class="pre">TCP_FASTOPEN</span></code>、<code class="docutils literal notranslate"><span class="pre">TCP_KEEPCNT</span></code> 可用。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>添加了 <code class="docutils literal notranslate"><span class="pre">TCP_NOTSENT_LOWAT</span></code>。</p>
<p>在 Windows 上，如果 Windows 运行时支持，则 <code class="docutils literal notranslate"><span class="pre">TCP_KEEPIDLE</span></code>、<code class="docutils literal notranslate"><span class="pre">TCP_KEEPINTVL</span></code> 可用。</p>
</div>
</dd></dl>

<dl class="data">
<dt id="socket.AF_CAN">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">AF_CAN</code><a class="headerlink" href="#socket.AF_CAN" title="永久链接至目标">¶</a></dt>
<dt id="socket.PF_CAN">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">PF_CAN</code><a class="headerlink" href="#socket.PF_CAN" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">SOL_CAN_*</code></dt>
<dt>
<code class="sig-name descname">CAN_*</code></dt>
<dd><p>此列表内的许多常量，记载在 Linux 文档中，同时也定义在本 socket 模块中。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： Linux &gt;= 2.6.25。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="socket.CAN_BCM">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">CAN_BCM</code><a class="headerlink" href="#socket.CAN_BCM" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">CAN_BCM_*</code></dt>
<dd><p>CAN 协议簇内的 CAN_BCM 是广播管理器（Bbroadcast Manager -- BCM）协议，广播管理器常量在 Linux 文档中有所记载，在本 socket 模块中也有定义。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： Linux &gt;= 2.6.25。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.4 新版功能.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="socket.CAN_RAW_FD_FRAMES">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">CAN_RAW_FD_FRAMES</code><a class="headerlink" href="#socket.CAN_RAW_FD_FRAMES" title="永久链接至目标">¶</a></dt>
<dd><p>在 CAN_RAW 套接字中启用 CAN FD 支持，默认是禁用的。它使应用程序可以发送 CAN 和 CAN FD 帧。但是，从套接字读取时，也必须同时接受 CAN 和 CAN FD 帧。</p>
<p>此常量在 Linux 文档中有所记载。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： Linux &gt;= 3.6。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.5 新版功能.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="socket.CAN_ISOTP">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">CAN_ISOTP</code><a class="headerlink" href="#socket.CAN_ISOTP" title="永久链接至目标">¶</a></dt>
<dd><p>CAN 协议簇中的 CAN_ISOTP 就是 ISO-TP (ISO 15765-2) 协议。ISO-TP 常量在 Linux 文档中有所记载。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： Linux &gt;= 2.6.25。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="socket.AF_PACKET">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">AF_PACKET</code><a class="headerlink" href="#socket.AF_PACKET" title="永久链接至目标">¶</a></dt>
<dt id="socket.PF_PACKET">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">PF_PACKET</code><a class="headerlink" href="#socket.PF_PACKET" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">PACKET_*</code></dt>
<dd><p>此列表内的许多常量，记载在 Linux 文档中，同时也定义在本 socket 模块中。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： Linux &gt;= 2.2。</p>
</dd></dl>

<dl class="data">
<dt id="socket.AF_RDS">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">AF_RDS</code><a class="headerlink" href="#socket.AF_RDS" title="永久链接至目标">¶</a></dt>
<dt id="socket.PF_RDS">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">PF_RDS</code><a class="headerlink" href="#socket.PF_RDS" title="永久链接至目标">¶</a></dt>
<dt id="socket.SOL_RDS">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">SOL_RDS</code><a class="headerlink" href="#socket.SOL_RDS" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">RDS_*</code></dt>
<dd><p>此列表内的许多常量，记载在 Linux 文档中，同时也定义在本 socket 模块中。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： Linux &gt;= 2.6.30。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="socket.SIO_RCVALL">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">SIO_RCVALL</code><a class="headerlink" href="#socket.SIO_RCVALL" title="永久链接至目标">¶</a></dt>
<dt id="socket.SIO_KEEPALIVE_VALS">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">SIO_KEEPALIVE_VALS</code><a class="headerlink" href="#socket.SIO_KEEPALIVE_VALS" title="永久链接至目标">¶</a></dt>
<dt id="socket.SIO_LOOPBACK_FAST_PATH">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">SIO_LOOPBACK_FAST_PATH</code><a class="headerlink" href="#socket.SIO_LOOPBACK_FAST_PATH" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">RCVALL_*</code></dt>
<dd><p>Windows 的 WSAIoctl() 的常量。这些常量用于套接字对象的 <a class="reference internal" href="#socket.socket.ioctl" title="socket.socket.ioctl"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ioctl()</span></code></a> 方法的参数。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.6 版更改: </span>添加了 <code class="docutils literal notranslate"><span class="pre">SIO_LOOPBACK_FAST_PATH</span></code>。</p>
</div>
</dd></dl>

<dl class="data">
<dt>
<code class="sig-name descname">TIPC_*</code></dt>
<dd><p>TIPC 相关常量，与 C socket API 导出的常量一致。更多信息请参阅 TIPC 文档。</p>
</dd></dl>

<dl class="data">
<dt id="socket.AF_ALG">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">AF_ALG</code><a class="headerlink" href="#socket.AF_ALG" title="永久链接至目标">¶</a></dt>
<dt id="socket.SOL_ALG">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">SOL_ALG</code><a class="headerlink" href="#socket.SOL_ALG" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">ALG_*</code></dt>
<dd><p>用于 Linux 内核加密算法的常量。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： Linux &gt;= 2.6.38。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.6 新版功能.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="socket.AF_VSOCK">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">AF_VSOCK</code><a class="headerlink" href="#socket.AF_VSOCK" title="永久链接至目标">¶</a></dt>
<dt id="socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">IOCTL_VM_SOCKETS_GET_LOCAL_CID</code><a class="headerlink" href="#socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">VMADDR*</code></dt>
<dt>
<code class="sig-name descname">SO_VM*</code></dt>
<dd><p>用于 Linux 宿主机/虚拟机通讯的常量。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： Linux &gt;= 4.8。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="socket.AF_LINK">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">AF_LINK</code><a class="headerlink" href="#socket.AF_LINK" title="永久链接至目标">¶</a></dt>
<dd><p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： BSD、OSX。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.4 新版功能.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="socket.has_ipv6">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">has_ipv6</code><a class="headerlink" href="#socket.has_ipv6" title="永久链接至目标">¶</a></dt>
<dd><p>本常量为一个布尔值，该值指示当前平台是否支持 IPv6。</p>
</dd></dl>

<dl class="data">
<dt id="socket.BDADDR_ANY">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">BDADDR_ANY</code><a class="headerlink" href="#socket.BDADDR_ANY" title="永久链接至目标">¶</a></dt>
<dt id="socket.BDADDR_LOCAL">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">BDADDR_LOCAL</code><a class="headerlink" href="#socket.BDADDR_LOCAL" title="永久链接至目标">¶</a></dt>
<dd><p>这些是字符串常量，包含蓝牙地址，这些地址具有特殊含义。例如，当用 <code class="xref py py-const docutils literal notranslate"><span class="pre">BTPROTO_RFCOMM</span></code> 指定绑定套接字时， <a class="reference internal" href="#socket.BDADDR_ANY" title="socket.BDADDR_ANY"><code class="xref py py-const docutils literal notranslate"><span class="pre">BDADDR_ANY</span></code></a> 表示“任何地址”。</p>
</dd></dl>

<dl class="data">
<dt id="socket.HCI_FILTER">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">HCI_FILTER</code><a class="headerlink" href="#socket.HCI_FILTER" title="永久链接至目标">¶</a></dt>
<dt id="socket.HCI_TIME_STAMP">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">HCI_TIME_STAMP</code><a class="headerlink" href="#socket.HCI_TIME_STAMP" title="永久链接至目标">¶</a></dt>
<dt id="socket.HCI_DATA_DIR">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">HCI_DATA_DIR</code><a class="headerlink" href="#socket.HCI_DATA_DIR" title="永久链接至目标">¶</a></dt>
<dd><p>与 <code class="xref py py-const docutils literal notranslate"><span class="pre">BTPROTO_HCI</span></code> 一起使用。 <a class="reference internal" href="#socket.HCI_FILTER" title="socket.HCI_FILTER"><code class="xref py py-const docutils literal notranslate"><span class="pre">HCI_FILTER</span></code></a> 在 NetBSD 或 DragonFlyBSD 上不可用。 <a class="reference internal" href="#socket.HCI_TIME_STAMP" title="socket.HCI_TIME_STAMP"><code class="xref py py-const docutils literal notranslate"><span class="pre">HCI_TIME_STAMP</span></code></a> 和 <a class="reference internal" href="#socket.HCI_DATA_DIR" title="socket.HCI_DATA_DIR"><code class="xref py py-const docutils literal notranslate"><span class="pre">HCI_DATA_DIR</span></code></a> 在 FreeBSD、NetBSD 或 DragonFlyBSD 上不可用。</p>
</dd></dl>

</div>
<div class="section" id="functions">
<h3>函数<a class="headerlink" href="#functions" title="永久链接至标题">¶</a></h3>
<div class="section" id="creating-sockets">
<h4>创建套接字<a class="headerlink" href="#creating-sockets" title="永久链接至标题">¶</a></h4>
<p>下列函数都能创建 <a class="reference internal" href="#socket-objects"><span class="std std-ref">套接字对象</span></a>.</p>
<dl class="function">
<dt id="socket.socket">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">socket</code><span class="sig-paren">(</span><em class="sig-param">family=AF_INET</em>, <em class="sig-param">type=SOCK_STREAM</em>, <em class="sig-param">proto=0</em>, <em class="sig-param">fileno=None</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket" title="永久链接至目标">¶</a></dt>
<dd><p>使用给定的地址簇、套接字类型和协议号创建一个新的套接字。地址簇应为 <a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a> （默认）、<a class="reference internal" href="#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET6</span></code></a>、<a class="reference internal" href="#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a>、<a class="reference internal" href="#socket.AF_CAN" title="socket.AF_CAN"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_CAN</span></code></a>、<a class="reference internal" href="#socket.AF_PACKET" title="socket.AF_PACKET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_PACKET</span></code></a> 或 <a class="reference internal" href="#socket.AF_RDS" title="socket.AF_RDS"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_RDS</span></code></a> 其中之一。套接字类型应为 <a class="reference internal" href="#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a> （默认）、<a class="reference internal" href="#socket.SOCK_DGRAM" title="socket.SOCK_DGRAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_DGRAM</span></code></a>、<a class="reference internal" href="#socket.SOCK_RAW" title="socket.SOCK_RAW"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_RAW</span></code></a> 或其他 <code class="docutils literal notranslate"><span class="pre">SOCK_</span></code> 常量之一。协议号通常为零，可以省略，或者在地址簇为 <a class="reference internal" href="#socket.AF_CAN" title="socket.AF_CAN"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_CAN</span></code></a> 的情况下，协议号应为 <code class="xref py py-const docutils literal notranslate"><span class="pre">CAN_RAW</span></code>、<a class="reference internal" href="#socket.CAN_BCM" title="socket.CAN_BCM"><code class="xref py py-const docutils literal notranslate"><span class="pre">CAN_BCM</span></code></a> 或 <a class="reference internal" href="#socket.CAN_ISOTP" title="socket.CAN_ISOTP"><code class="xref py py-const docutils literal notranslate"><span class="pre">CAN_ISOTP</span></code></a> 之一。</p>
<p>如果指定了 <em>fileno</em>，那么将从这一指定的文件描述符中自动检测 <em>family</em>、<em>type</em> 和 <em>proto</em> 的值。如果调用本函数时显式指定了 <em>family</em>、<em>type</em> 或 <em>proto</em> 参数，可以覆盖自动检测的值。这只会影响 Python 表示诸如 <a class="reference internal" href="#socket.socket.getpeername" title="socket.socket.getpeername"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.getpeername()</span></code></a> 一类函数的返回值的方式，而不影响实际的操作系统资源。与 <a class="reference internal" href="#socket.fromfd" title="socket.fromfd"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket.fromfd()</span></code></a> 不同，<em>fileno</em> 将返回原先的套接字，而不是复制出新的套接字。这有助于在分离的套接字上调用 <a class="reference internal" href="#socket.close" title="socket.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.close()</span></code></a> 来关闭它。</p>
<p>新创建的套接字是 <a class="reference internal" href="os.html#fd-inheritance"><span class="std std-ref">不可继承的</span></a>。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>添加了 AF_CAN 簇。添加了 AF_RDS 簇。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.4 版更改: </span>添加了 CAN_BCM 协议。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.4 版更改: </span>返回的套接字现在是不可继承的。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>添加了 CAN_ISOTP 协议。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>当将 <a class="reference internal" href="#socket.SOCK_NONBLOCK" title="socket.SOCK_NONBLOCK"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_NONBLOCK</span></code></a> 或 <a class="reference internal" href="#socket.SOCK_CLOEXEC" title="socket.SOCK_CLOEXEC"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_CLOEXEC</span></code></a> 标志位应用于 <em>type</em> 上时，它们会被清除，且 <a class="reference internal" href="#socket.socket.type" title="socket.socket.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">socket.type</span></code></a> 反映不出它们。但它们仍将传递给底层系统的 <cite>socket()</cite> 调用。因此，</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">sock</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span>
    <span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span>
    <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span> <span class="o">|</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_NONBLOCK</span><span class="p">)</span>
</pre></div>
</div>
<p>仍将在支持 <code class="docutils literal notranslate"><span class="pre">SOCK_NONBLOCK</span></code> 的系统上创建一个非阻塞的套接字，但是 <code class="docutils literal notranslate"><span class="pre">sock.type</span></code> 会被置为 <code class="docutils literal notranslate"><span class="pre">socket.SOCK_STREAM</span></code>。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.socketpair">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">socketpair</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">family</em><span class="optional">[</span>, <em class="sig-param">type</em><span class="optional">[</span>, <em class="sig-param">proto</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socketpair" title="永久链接至目标">¶</a></dt>
<dd><p>构建一对已连接的套接字对象，使用给定的地址簇、套接字类型和协议号。地址簇、套接字类型和协议号与上述 <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a> 函数相同。默认地址簇为 <a class="reference internal" href="#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a> （需要当前平台支持，不支持则默认为 <a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a> ）。</p>
<p>新创建的套接字都是 <a class="reference internal" href="os.html#fd-inheritance"><span class="std std-ref">不可继承的</span></a>。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span>现在，返回的套接字对象支持全部套接字 API，而不是全部 API 的一个子集。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.4 版更改: </span>返回的套接字现在都是不可继承的。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>添加了 Windows 支持。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.create_connection">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">create_connection</code><span class="sig-paren">(</span><em class="sig-param">address</em><span class="optional">[</span>, <em class="sig-param">timeout</em><span class="optional">[</span>, <em class="sig-param">source_address</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.create_connection" title="永久链接至目标">¶</a></dt>
<dd><p>连接到一个 TCP 服务，该服务正在侦听 Internet <em>address</em> （用二元组 <code class="docutils literal notranslate"><span class="pre">(host,</span> <span class="pre">port)</span></code> 表示）。连接后返回套接字对象。这是比 <a class="reference internal" href="#socket.socket.connect" title="socket.socket.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.connect()</span></code></a> 更高级的函数：如果 <em>host</em> 是非数字主机名，它将尝试从 <a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_INET</span></code></a> 和 <a class="reference internal" href="#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_INET6</span></code></a> 解析它，然后依次尝试连接到所有可能的地址，直到连接成功。这使得编写兼容 IPv4 和 IPv6 的客户端变得容易。</p>
<p>传入可选参数 <em>timeout</em> 可以在套接字实例上设置超时（在尝试连接前）。如果未提供 <em>timeout</em>，则使用由 <a class="reference internal" href="#socket.getdefaulttimeout" title="socket.getdefaulttimeout"><code class="xref py py-func docutils literal notranslate"><span class="pre">getdefaulttimeout()</span></code></a> 返回的全局默认超时设置。</p>
<p>如果提供了 <em>source_address</em>，它必须为二元组 <code class="docutils literal notranslate"><span class="pre">(host,</span> <span class="pre">port)</span></code>，以便套接字在连接之前绑定为其源地址。如果 host 或 port 分别为 '' 或 0，则使用操作系统默认行为。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span>添加了*source_address* 参数</p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.fromfd">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">fromfd</code><span class="sig-paren">(</span><em class="sig-param">fd</em>, <em class="sig-param">family</em>, <em class="sig-param">type</em>, <em class="sig-param">proto=0</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.fromfd" title="永久链接至目标">¶</a></dt>
<dd><p>复制文件描述符 <em>fd</em> （一个由文件对象的 <code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code> 方法返回的整数），然后从结果中构建一个套接字对象。地址簇、套接字类型和协议号与上述 <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a> 函数相同。文件描述符应指向一个套接字，但不会专门去检查——如果文件描述符是无效的，则对该对象的后续操作可能会失败。本函数很少用到，但是在将套接字作为标准输入或输出传递给程序（如 Unix inet 守护程序启动的服务器）时，可以使用本函数获取或设置套接字选项。套接字须处于阻塞模式。</p>
<p>新创建的套接字是 <a class="reference internal" href="os.html#fd-inheritance"><span class="std std-ref">不可继承的</span></a>。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.4 版更改: </span>返回的套接字现在是不可继承的。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.fromshare">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">fromshare</code><span class="sig-paren">(</span><em class="sig-param">data</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.fromshare" title="永久链接至目标">¶</a></dt>
<dd><p>根据 <a class="reference internal" href="#socket.socket.share" title="socket.socket.share"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.share()</span></code></a> 方法获得的数据实例化套接字。套接字须处于阻塞模式。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>: Windows。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="socket.SocketType">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">SocketType</code><a class="headerlink" href="#socket.SocketType" title="永久链接至目标">¶</a></dt>
<dd><p>这是一个 Python 类型对象，表示套接字对象的类型。它等同于 <code class="docutils literal notranslate"><span class="pre">type(socket(...))</span></code>。</p>
</dd></dl>

</div>
<div class="section" id="other-functions">
<h4>其他功能<a class="headerlink" href="#other-functions" title="永久链接至标题">¶</a></h4>
<p><a class="reference internal" href="#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> 模块还提供各种与网络相关的服务：</p>
<dl class="function">
<dt id="socket.close">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">close</code><span class="sig-paren">(</span><em class="sig-param">fd</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.close" title="永久链接至目标">¶</a></dt>
<dd><p>关闭一个套接字文件描述符。它类似于 <a class="reference internal" href="os.html#os.close" title="os.close"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.close()</span></code></a>，但专用于套接字。在某些平台上（特别是在 Windows 上），<a class="reference internal" href="os.html#os.close" title="os.close"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.close()</span></code></a> 对套接字文件描述符无效。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.getaddrinfo">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">getaddrinfo</code><span class="sig-paren">(</span><em class="sig-param">host</em>, <em class="sig-param">port</em>, <em class="sig-param">family=0</em>, <em class="sig-param">type=0</em>, <em class="sig-param">proto=0</em>, <em class="sig-param">flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.getaddrinfo" title="永久链接至目标">¶</a></dt>
<dd><p>将 <em>host</em>/<em>port</em> 参数转换为 5 元组的序列，其中包含创建（连接到某服务的）套接字所需的所有参数。<em>host</em> 是域名，是字符串格式的 IPv4/v6 地址或 <code class="docutils literal notranslate"><span class="pre">None</span></code>。<em>port</em> 是字符串格式的服务名称，如 <code class="docutils literal notranslate"><span class="pre">'http'</span></code> 、端口号（数字）或 <code class="docutils literal notranslate"><span class="pre">None</span></code>。传入 <code class="docutils literal notranslate"><span class="pre">None</span></code> 作为 <em>host</em> 和 <em>port</em> 的值，相当于将 <code class="docutils literal notranslate"><span class="pre">NULL</span></code> 传递给底层 C API。</p>
<p>可以指定 <em>family</em>、<em>type</em> 和 <em>proto</em> 参数，以缩小返回的地址列表。向这些参数分别传入 0 表示保留全部结果范围。<em>flags</em> 参数可以是 <code class="docutils literal notranslate"><span class="pre">AI_*</span></code> 常量中的一个或多个，它会影响结果的计算和返回。例如，<code class="xref py py-const docutils literal notranslate"><span class="pre">AI_NUMERICHOST</span></code> 会禁用域名解析，此时如果 <em>host</em> 是域名，则会抛出错误。</p>
<p>本函数返回的 5 元组列表具有以下结构：</p>
<p><code class="docutils literal notranslate"><span class="pre">(family,</span> <span class="pre">type,</span> <span class="pre">proto,</span> <span class="pre">canonname,</span> <span class="pre">sockaddr)</span></code></p>
<p>在这些元组中，<em>family</em>、<em>type</em>、<em>proto</em> 都是整数，可以用于传递给 <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a> 函数。如果 <em>flags</em> 参数有一部分是 <code class="xref py py-const docutils literal notranslate"><span class="pre">AI_CANONNAME</span></code>，那么 <em>canonname</em> 将是表示 <em>host</em> 的规范名称的字符串。否则 <em>canonname</em> 将为空。<em>sockaddr</em> 是一个表示套接字地址的元组，具体格式取决于返回的 <em>family</em> （对于 <a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a>，是一个 <code class="docutils literal notranslate"><span class="pre">(address,</span> <span class="pre">port)</span></code> 二元组，对于 <a class="reference internal" href="#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET6</span></code></a>，是一个 <code class="docutils literal notranslate"><span class="pre">(address,</span> <span class="pre">port,</span> <span class="pre">flow</span> <span class="pre">info,</span> <span class="pre">scope</span> <span class="pre">id)</span></code> 四元组），可以用于传递给 <a class="reference internal" href="#socket.socket.connect" title="socket.socket.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.connect()</span></code></a> 方法。</p>
<p>下面的示例获取了 TCP 连接地址信息，假设该连接通过 80 端口连接至 <code class="docutils literal notranslate"><span class="pre">example.org</span></code> （如果系统未启用 IPv6，则结果可能会不同）：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">socket</span><span class="o">.</span><span class="n">getaddrinfo</span><span class="p">(</span><span class="s2">&quot;example.org&quot;</span><span class="p">,</span> <span class="mi">80</span><span class="p">,</span> <span class="n">proto</span><span class="o">=</span><span class="n">socket</span><span class="o">.</span><span class="n">IPPROTO_TCP</span><span class="p">)</span>
<span class="go">[(&lt;AddressFamily.AF_INET6: 10&gt;, &lt;SocketType.SOCK_STREAM: 1&gt;,</span>
<span class="go"> 6, &#39;&#39;, (&#39;2606:2800:220:1:248:1893:25c8:1946&#39;, 80, 0, 0)),</span>
<span class="go"> (&lt;AddressFamily.AF_INET: 2&gt;, &lt;SocketType.SOCK_STREAM: 1&gt;,</span>
<span class="go"> 6, &#39;&#39;, (&#39;93.184.216.34&#39;, 80))]</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span>现在可以使用关键字参数的形式来传递参数。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>对于 IPv6 多播地址，表示地址的字符串将不包含 <code class="docutils literal notranslate"><span class="pre">%scope</span></code> 部分。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.getfqdn">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">getfqdn</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">name</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.getfqdn" title="永久链接至目标">¶</a></dt>
<dd><p>返回 <em>name</em> 的全限定域名 (Fully Qualified Domain Name -- FQDN)。如果 <em>name</em> 省略或为空，则将其解释为本地主机。为了查找全限定名称，首先将检查由 <a class="reference internal" href="#socket.gethostbyaddr" title="socket.gethostbyaddr"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostbyaddr()</span></code></a> 返回的主机名，然后是主机的别名（如果存在）。选中第一个包含句点的名字。如果无法获取全限定域名，则返回由 <a class="reference internal" href="#socket.gethostname" title="socket.gethostname"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostname()</span></code></a> 返回的主机名。</p>
</dd></dl>

<dl class="function">
<dt id="socket.gethostbyname">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">gethostbyname</code><span class="sig-paren">(</span><em class="sig-param">hostname</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.gethostbyname" title="永久链接至目标">¶</a></dt>
<dd><p>将主机名转换为 IPv4 地址格式。IPv4 地址以字符串格式返回，如 <code class="docutils literal notranslate"><span class="pre">'100.50.200.5'</span></code>。如果主机名本身是 IPv4 地址，则原样返回。更完整的接口请参考 <a class="reference internal" href="#socket.gethostbyname_ex" title="socket.gethostbyname_ex"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostbyname_ex()</span></code></a>。<a class="reference internal" href="#socket.gethostbyname" title="socket.gethostbyname"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostbyname()</span></code></a> 不支持 IPv6 域名解析，应使用 <a class="reference internal" href="#socket.getaddrinfo" title="socket.getaddrinfo"><code class="xref py py-func docutils literal notranslate"><span class="pre">getaddrinfo()</span></code></a> 来支持 IPv4/v6 双协议栈。</p>
</dd></dl>

<dl class="function">
<dt id="socket.gethostbyname_ex">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">gethostbyname_ex</code><span class="sig-paren">(</span><em class="sig-param">hostname</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.gethostbyname_ex" title="永久链接至目标">¶</a></dt>
<dd><p>将主机名转换为 IPv4 地址格式的扩展接口。返回三元组 <code class="docutils literal notranslate"><span class="pre">(hostname,</span> <span class="pre">aliaslist,</span> <span class="pre">ipaddrlist)</span></code>，其中 <em>hostname</em> 是响应给定 <em>ip_address</em> 的主要主机名，<em>aliaslist</em> 是相同地址的其他可用主机名的列表（可能为空），而 <em>ipaddrlist</em> 是 IPv4 地址列表，包含相同主机名、相同接口的不同地址（通常是一个地址，但不总是如此）。<a class="reference internal" href="#socket.gethostbyname_ex" title="socket.gethostbyname_ex"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostbyname_ex()</span></code></a> 不支持 IPv6 名称解析，应使用 <a class="reference internal" href="#socket.getaddrinfo" title="socket.getaddrinfo"><code class="xref py py-func docutils literal notranslate"><span class="pre">getaddrinfo()</span></code></a> 来支持 IPv4/v6 双协议栈。</p>
</dd></dl>

<dl class="function">
<dt id="socket.gethostname">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">gethostname</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.gethostname" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个字符串，包含当前正在运行 Python 解释器的机器的主机名。</p>
<p>注意： <a class="reference internal" href="#socket.gethostname" title="socket.gethostname"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostname()</span></code></a> 并不总是返回全限定域名，必要的话请使用 <a class="reference internal" href="#socket.getfqdn" title="socket.getfqdn"><code class="xref py py-func docutils literal notranslate"><span class="pre">getfqdn()</span></code></a>。</p>
</dd></dl>

<dl class="function">
<dt id="socket.gethostbyaddr">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">gethostbyaddr</code><span class="sig-paren">(</span><em class="sig-param">ip_address</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.gethostbyaddr" title="永久链接至目标">¶</a></dt>
<dd><p>返回三元组 <code class="docutils literal notranslate"><span class="pre">(hostname,</span> <span class="pre">aliaslist,</span> <span class="pre">ipaddrlist)</span></code>，其中 <em>hostname</em> 是响应给定 <em>ip_address</em> 的主要主机名，<em>aliaslist</em> 是相同地址的其他可用主机名的列表（可能为空），而 <em>ipaddrlist</em> 是 IPv4/v6 地址列表，包含相同主机名、相同接口的不同地址（很可能仅包含一个地址）。要查询全限定域名，请使用函数 <a class="reference internal" href="#socket.getfqdn" title="socket.getfqdn"><code class="xref py py-func docutils literal notranslate"><span class="pre">getfqdn()</span></code></a>。<a class="reference internal" href="#socket.gethostbyaddr" title="socket.gethostbyaddr"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostbyaddr()</span></code></a> 支持 IPv4 和 IPv6。</p>
</dd></dl>

<dl class="function">
<dt id="socket.getnameinfo">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">getnameinfo</code><span class="sig-paren">(</span><em class="sig-param">sockaddr</em>, <em class="sig-param">flags</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.getnameinfo" title="永久链接至目标">¶</a></dt>
<dd><p>将套接字地址 <em>sockaddr</em> 转换为二元组 <code class="docutils literal notranslate"><span class="pre">(host,</span> <span class="pre">port)</span></code>。<em>host</em> 的形式可能是全限定域名，或是由数字表示的地址，具体取决于 <em>flags</em> 的设置。同样，<em>port</em> 可以包含字符串格式的端口名称或数字格式的端口号。</p>
<p>对于 IPv6 地址，如果 <em>sockaddr</em> 包含有意义的 <em>scopeid</em>，则将 <code class="docutils literal notranslate"><span class="pre">%scope</span></code> 附加到 host 部分。这种情况通常发生在多播地址上。</p>
</dd></dl>

<dl class="function">
<dt id="socket.getprotobyname">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">getprotobyname</code><span class="sig-paren">(</span><em class="sig-param">protocolname</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.getprotobyname" title="永久链接至目标">¶</a></dt>
<dd><p>将 Internet 协议名称（如 <code class="docutils literal notranslate"><span class="pre">'icmp'</span></code> ）转换为常量，该常量适用于 <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a> 函数的第三个（可选）参数。通常只有在 &quot;raw&quot; 模式 (<a class="reference internal" href="#socket.SOCK_RAW" title="socket.SOCK_RAW"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_RAW</span></code></a>) 中打开的套接字才需要使用该常量。对于正常的套接字模式，协议省略或为零时，会自动选择正确的协议。</p>
</dd></dl>

<dl class="function">
<dt id="socket.getservbyname">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">getservbyname</code><span class="sig-paren">(</span><em class="sig-param">servicename</em><span class="optional">[</span>, <em class="sig-param">protocolname</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.getservbyname" title="永久链接至目标">¶</a></dt>
<dd><p>将 Internet 服务名称和协议名称转换为该服务的端口号。协议名称是可选的，如果提供的话应为 <code class="docutils literal notranslate"><span class="pre">'tcp'</span></code> 或 <code class="docutils literal notranslate"><span class="pre">'udp'</span></code>，否则将匹配出所有协议。</p>
</dd></dl>

<dl class="function">
<dt id="socket.getservbyport">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">getservbyport</code><span class="sig-paren">(</span><em class="sig-param">port</em><span class="optional">[</span>, <em class="sig-param">protocolname</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.getservbyport" title="永久链接至目标">¶</a></dt>
<dd><p>将 Internet 端口号和协议名称转换为该服务的服务名称。协议名称是可选的，如果提供的话应为 <code class="docutils literal notranslate"><span class="pre">'tcp'</span></code> 或 <code class="docutils literal notranslate"><span class="pre">'udp'</span></code>，否则将匹配出所有协议。</p>
</dd></dl>

<dl class="function">
<dt id="socket.ntohl">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">ntohl</code><span class="sig-paren">(</span><em class="sig-param">x</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.ntohl" title="永久链接至目标">¶</a></dt>
<dd><p>将 32 位正整数从网络字节序转换为主机字节序。在主机字节序与网络字节序相同的计算机上，这是一个空操作。字节序不同将执行 4 字节交换操作。</p>
</dd></dl>

<dl class="function">
<dt id="socket.ntohs">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">ntohs</code><span class="sig-paren">(</span><em class="sig-param">x</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.ntohs" title="永久链接至目标">¶</a></dt>
<dd><p>将 16 位正整数从网络字节序转换为主机字节序。在主机字节序与网络字节序相同的计算机上，这是一个空操作。字节序不同将执行 2 字节交换操作。</p>
<div class="deprecated">
<p><span class="versionmodified deprecated">3.7 版后已移除: </span>如果 <em>x</em> 不符合 16 位无符号整数，但符合 C 语言的正整数，则它会被静默截断为 16 位无符号整数。此静默截断功能已弃用，未来版本的 Python 将对此抛出异常。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.htonl">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">htonl</code><span class="sig-paren">(</span><em class="sig-param">x</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.htonl" title="永久链接至目标">¶</a></dt>
<dd><p>将 32 位正整数从主机字节序转换为网络字节序。在主机字节序与网络字节序相同的计算机上，这是一个空操作。字节序不同将执行 4 字节交换操作。</p>
</dd></dl>

<dl class="function">
<dt id="socket.htons">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">htons</code><span class="sig-paren">(</span><em class="sig-param">x</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.htons" title="永久链接至目标">¶</a></dt>
<dd><p>将 16 位正整数从主机字节序转换为网络字节序。在主机字节序与网络字节序相同的计算机上，这是一个空操作。字节序不同将执行 2 字节交换操作。</p>
<div class="deprecated">
<p><span class="versionmodified deprecated">3.7 版后已移除: </span>如果 <em>x</em> 不符合 16 位无符号整数，但符合 C 语言的正整数，则它会被静默截断为 16 位无符号整数。此静默截断功能已弃用，未来版本的 Python 将对此抛出异常。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.inet_aton">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">inet_aton</code><span class="sig-paren">(</span><em class="sig-param">ip_string</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.inet_aton" title="永久链接至目标">¶</a></dt>
<dd><p>将 IPv4 地址从点分十进制字符串格式（如 '123.45.67.89' ）转换为 32 位压缩二进制格式，转换后为字节对象，长度为四个字符。与那些使用标准 C 库，且需要 <code class="xref c c-type docutils literal notranslate"><span class="pre">struct</span> <span class="pre">in_addr</span></code> 类型的对象的程序交换信息时，此功能很有用。 该类型即此函数返回的 32 位压缩二进制的 C 类型。</p>
<p><a class="reference internal" href="#socket.inet_aton" title="socket.inet_aton"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_aton()</span></code></a> 也接受句点数少于三的字符串，详情请参阅 Unix 手册 <em class="manpage">inet(3)</em>。</p>
<p>如果传入本函数的 IPv4 地址字符串无效，则抛出 <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>。注意，具体什么样的地址有效取决于 <code class="xref c c-func docutils literal notranslate"><span class="pre">inet_aton()</span></code> 的底层 C 实现。</p>
<p><a class="reference internal" href="#socket.inet_aton" title="socket.inet_aton"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_aton()</span></code></a> 不支持 IPv6，在 IPv4/v6 双协议栈下应使用 <a class="reference internal" href="#socket.inet_pton" title="socket.inet_pton"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_pton()</span></code></a> 来代替。</p>
</dd></dl>

<dl class="function">
<dt id="socket.inet_ntoa">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">inet_ntoa</code><span class="sig-paren">(</span><em class="sig-param">packed_ip</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.inet_ntoa" title="永久链接至目标">¶</a></dt>
<dd><p>将 32 位压缩 IPv4 地址（一个 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">类字节对象</span></a>，长 4 个字节）转换为标准的点分十进制字符串形式（如 '123.45.67.89' ）。与那些使用标准 C 库，且需要 <code class="xref c c-type docutils literal notranslate"><span class="pre">struct</span> <span class="pre">in_addr</span></code> 类型的对象的程序交换信息时，本函数很有用。 该类型即本函数参数中的 32 位压缩二进制数据的 C 类型。</p>
<p>如果传入本函数的字节序列长度不是 4 个字节，则抛出 <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>。<a class="reference internal" href="#socket.inet_ntoa" title="socket.inet_ntoa"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_ntoa()</span></code></a> 不支持 IPv6，在 IPv4/v6 双协议栈下应使用 <a class="reference internal" href="#socket.inet_ntop" title="socket.inet_ntop"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_ntop()</span></code></a> 来代替。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>现在支持可写的 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">字节类对象</span></a>。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.inet_pton">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">inet_pton</code><span class="sig-paren">(</span><em class="sig-param">address_family</em>, <em class="sig-param">ip_string</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.inet_pton" title="永久链接至目标">¶</a></dt>
<dd><p>将特定地址簇的 IP 地址（字符串）转换为压缩二进制格式。当库或网络协议需要接受 <code class="xref c c-type docutils literal notranslate"><span class="pre">struct</span> <span class="pre">in_addr</span></code> 类型的对象（类似 <a class="reference internal" href="#socket.inet_aton" title="socket.inet_aton"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_aton()</span></code></a> ）或 <code class="xref c c-type docutils literal notranslate"><span class="pre">struct</span> <span class="pre">in6_addr</span></code> 类型的对象时，<a class="reference internal" href="#socket.inet_pton" title="socket.inet_pton"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_pton()</span></code></a> 很有用。</p>
<p>目前 <em>address_family</em> 支持 <a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a> 和 <a class="reference internal" href="#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET6</span></code></a>。如果 IP 地址字符串 <em>ip_string</em> 无效，则抛出 <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>。注意，具体什么地址有效取决于 <em>address_family</em> 的值和 <code class="xref c c-func docutils literal notranslate"><span class="pre">inet_pton()</span></code> 的底层实现。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： Unix（可能非所有平台都可用）、Windows。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.4 版更改: </span>添加了 Windows 支持</p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.inet_ntop">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">inet_ntop</code><span class="sig-paren">(</span><em class="sig-param">address_family</em>, <em class="sig-param">packed_ip</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.inet_ntop" title="永久链接至目标">¶</a></dt>
<dd><p>将压缩 IP 地址（一个 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">类字节对象</span></a>，数个字节长）转换为标准的、特定地址簇的字符串形式（如 <code class="docutils literal notranslate"><span class="pre">'7.10.0.5'</span></code> 或 <code class="docutils literal notranslate"><span class="pre">'5aef:2b::8'</span></code> ）。当库或网络协议返回 <code class="xref c c-type docutils literal notranslate"><span class="pre">struct</span> <span class="pre">in_addr</span></code> 类型的对象（类似 <a class="reference internal" href="#socket.inet_ntoa" title="socket.inet_ntoa"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_ntoa()</span></code></a> ）或 <code class="xref c c-type docutils literal notranslate"><span class="pre">struct</span> <span class="pre">in6_addr</span></code> 类型的对象时，<a class="reference internal" href="#socket.inet_ntop" title="socket.inet_ntop"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_ntop()</span></code></a> 很有用。</p>
<p>目前 <em>address_family</em> 支持 <a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a> 和 <a class="reference internal" href="#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET6</span></code></a>。如果字节对象 <em>packed_ip</em> 与指定的地址簇长度不符，则抛出 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。针对 <a class="reference internal" href="#socket.inet_ntop" title="socket.inet_ntop"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_ntop()</span></code></a> 调用的错误则抛出 <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： Unix（可能非所有平台都可用）、Windows。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.4 版更改: </span>添加了 Windows 支持</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>现在支持可写的 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">字节类对象</span></a>。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.CMSG_LEN">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">CMSG_LEN</code><span class="sig-paren">(</span><em class="sig-param">length</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.CMSG_LEN" title="永久链接至目标">¶</a></dt>
<dd><p>返回给定 <em>length</em> 所关联数据的辅助数据项的总长度（不带尾部填充）。此值通常用作 <a class="reference internal" href="#socket.socket.recvmsg" title="socket.socket.recvmsg"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recvmsg()</span></code></a> 接收一个辅助数据项的缓冲区大小，但是 <span class="target" id="index-31"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3542.html"><strong>RFC 3542</strong></a> 要求可移植应用程序使用 <a class="reference internal" href="#socket.CMSG_SPACE" title="socket.CMSG_SPACE"><code class="xref py py-func docutils literal notranslate"><span class="pre">CMSG_SPACE()</span></code></a>，以此将尾部填充的空间计入，即使该项在缓冲区的最后。如果 <em>length</em> 超出允许范围，则抛出 <a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： 大多数 Unix 平台，其他平台也可能可用。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.CMSG_SPACE">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">CMSG_SPACE</code><span class="sig-paren">(</span><em class="sig-param">length</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.CMSG_SPACE" title="永久链接至目标">¶</a></dt>
<dd><p>返回 <a class="reference internal" href="#socket.socket.recvmsg" title="socket.socket.recvmsg"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recvmsg()</span></code></a> 所需的缓冲区大小，以接收给定 <em>length</em> 所关联数据的辅助数据项，带有尾部填充。接收多个项目所需的缓冲区空间是关联数据长度的 <a class="reference internal" href="#socket.CMSG_SPACE" title="socket.CMSG_SPACE"><code class="xref py py-func docutils literal notranslate"><span class="pre">CMSG_SPACE()</span></code></a> 值的总和。如果 <em>length</em> 超出允许范围，则抛出 <a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>。</p>
<p>请注意，某些系统可能支持辅助数据，但不提供本函数。还需注意，如果使用本函数的结果来设置缓冲区大小，可能无法精确限制可接收的辅助数据量，因为可能会有其他数据写入尾部填充区域。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： 大多数 Unix 平台，其他平台也可能可用。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.getdefaulttimeout">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">getdefaulttimeout</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.getdefaulttimeout" title="永久链接至目标">¶</a></dt>
<dd><p>返回用于新套接字对象的默认超时（以秒为单位的浮点数）。值 <code class="docutils literal notranslate"><span class="pre">None</span></code> 表示新套接字对象没有超时。首次导入 socket 模块时，默认值为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
</dd></dl>

<dl class="function">
<dt id="socket.setdefaulttimeout">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">setdefaulttimeout</code><span class="sig-paren">(</span><em class="sig-param">timeout</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.setdefaulttimeout" title="永久链接至目标">¶</a></dt>
<dd><p>设置用于新套接字对象的默认超时（以秒为单位的浮点数）。首次导入 socket 模块时，默认值为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。可能的取值及其各自的含义请参阅 <a class="reference internal" href="#socket.socket.settimeout" title="socket.socket.settimeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">settimeout()</span></code></a>。</p>
</dd></dl>

<dl class="function">
<dt id="socket.sethostname">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">sethostname</code><span class="sig-paren">(</span><em class="sig-param">name</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.sethostname" title="永久链接至目标">¶</a></dt>
<dd><p>将计算机的主机名设置为 <em>name</em>。如果权限不足将抛出 <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>: Unix。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.if_nameindex">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">if_nameindex</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.if_nameindex" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个列表，包含网络接口（网卡）信息二元组（整数索引，名称字符串）。系统调用失败则抛出 <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>: Unix。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.if_nametoindex">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">if_nametoindex</code><span class="sig-paren">(</span><em class="sig-param">if_name</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.if_nametoindex" title="永久链接至目标">¶</a></dt>
<dd><p>返回网络接口名称相对应的索引号。如果没有所给名称的接口，则抛出 <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>: Unix。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.if_indextoname">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">if_indextoname</code><span class="sig-paren">(</span><em class="sig-param">if_index</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.if_indextoname" title="永久链接至目标">¶</a></dt>
<dd><p>返回网络接口索引号相对应的接口名称。如果没有所给索引号的接口，则抛出 <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>: Unix。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

</div>
</div>
</div>
<div class="section" id="socket-objects">
<span id="id1"></span><h2>套接字对象<a class="headerlink" href="#socket-objects" title="永久链接至标题">¶</a></h2>
<p>套接字对象具有以下方法。除了 <a class="reference internal" href="#socket.socket.makefile" title="socket.socket.makefile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">makefile()</span></code></a>，其他都与套接字专用的 Unix 系统调用相对应。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span>添加了对 <a class="reference internal" href="../glossary.html#term-context-manager"><span class="xref std std-term">上下文管理器</span></a> 协议的支持。退出上下文管理器与调用 <a class="reference internal" href="#socket.close" title="socket.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> 等效。</p>
</div>
<dl class="method">
<dt id="socket.socket.accept">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">accept</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.accept" title="永久链接至目标">¶</a></dt>
<dd><p>接受一个连接。此 scoket 必须绑定到一个地址上并且监听连接。返回值是一个 <code class="docutils literal notranslate"><span class="pre">(conn,</span> <span class="pre">address)</span></code> 对，其中 <em>conn</em> 是一个 <em>新</em> 的套接字对象，用于在此连接上收发数据，<em>address</em> 是连接另一端的套接字所绑定的地址。</p>
<p>新创建的套接字是 <a class="reference internal" href="os.html#fd-inheritance"><span class="std std-ref">不可继承的</span></a>。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.4 版更改: </span>该套接字现在是不可继承的。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 <a class="reference internal" href="exceptions.html#InterruptedError" title="InterruptedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterruptedError</span></code></a> 异常 (原因详见 <span class="target" id="index-32"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0475"><strong>PEP 475</strong></a>)。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.bind">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">bind</code><span class="sig-paren">(</span><em class="sig-param">address</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.bind" title="永久链接至目标">¶</a></dt>
<dd><p>将套接字绑定到 <em>address</em>。套接字必须尚未绑定。（ <em>address</em> 的格式取决于地址簇 —— 参见上文）</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.close">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.close" title="永久链接至目标">¶</a></dt>
<dd><p>将套接字标记为关闭。当 <a class="reference internal" href="#socket.socket.makefile" title="socket.socket.makefile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">makefile()</span></code></a> 创建的所有文件对象都关闭时，底层系统资源（如文件描述符）也将关闭。一旦上述情况发生，将来对套接字对象的所有操作都会失败。对端将接收不到任何数据（清空队列数据后）。</p>
<p>垃圾回收时，套接字会自动关闭，但建议显式 <a class="reference internal" href="#socket.close" title="socket.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> 它们，或在它们周围使用 <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> 语句。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.6 版更改: </span>现在，如果底层的 <code class="xref c c-func docutils literal notranslate"><span class="pre">close()</span></code> 调用出错，会抛出 <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>。</p>
</div>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p><a class="reference internal" href="#socket.close" title="socket.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> 释放与连接相关联的资源，但不一定立即关闭连接。如果需要及时关闭连接，请在调用 <a class="reference internal" href="#socket.close" title="socket.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> 之前调用 <a class="reference internal" href="#socket.socket.shutdown" title="socket.socket.shutdown"><code class="xref py py-meth docutils literal notranslate"><span class="pre">shutdown()</span></code></a>。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.connect">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">connect</code><span class="sig-paren">(</span><em class="sig-param">address</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.connect" title="永久链接至目标">¶</a></dt>
<dd><p>连接到 <em>address</em> 处的远程套接字。（ <em>address</em> 的格式取决于地址簇 —— 参见上文）</p>
<p>如果连接被信号中断，则本方法将等待，直到连接完成。如果信号处理程序未抛出异常，且套接字阻塞中或已超时，则在超时后抛出 <a class="reference internal" href="#socket.timeout" title="socket.timeout"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.timeout</span></code></a>。对于非阻塞套接字，如果连接被信号中断，则本方法将抛出 <a class="reference internal" href="exceptions.html#InterruptedError" title="InterruptedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterruptedError</span></code></a> 异常（或信号处理程序抛出的异常）。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>本方法现在将等待，直到连接完成，而不是在以下情况抛出 <a class="reference internal" href="exceptions.html#InterruptedError" title="InterruptedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterruptedError</span></code></a> 异常。该情况为，连接被信号中断，信号处理程序未抛出异常，且套接字阻塞中或已超时（具体解释请参阅 <span class="target" id="index-33"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0475"><strong>PEP 475</strong></a> ）。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.connect_ex">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">connect_ex</code><span class="sig-paren">(</span><em class="sig-param">address</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.connect_ex" title="永久链接至目标">¶</a></dt>
<dd><p>类似于 <code class="docutils literal notranslate"><span class="pre">connect(address)</span></code>，但是对于 C 级别的 <code class="xref c c-func docutils literal notranslate"><span class="pre">connect()</span></code> 调用返回的错误，本函数将返回错误指示器，而不是抛出异常（对于其他问题，如“找不到主机”，仍然可以抛出异常）。如果操作成功，则错误指示器为  <code class="docutils literal notranslate"><span class="pre">0</span></code>，否则为 <code class="xref c c-data docutils literal notranslate"><span class="pre">errno</span></code> 变量的值。这对支持如异步连接很有用。</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.detach">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">detach</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.detach" title="永久链接至目标">¶</a></dt>
<dd><p>将套接字对象置于关闭状态，而底层的文件描述符实际并不关闭。返回该文件描述符，使其可以重新用于其他目的。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.dup">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">dup</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.dup" title="永久链接至目标">¶</a></dt>
<dd><p>创建套接字的副本。</p>
<p>新创建的套接字是 <a class="reference internal" href="os.html#fd-inheritance"><span class="std std-ref">不可继承的</span></a>。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.4 版更改: </span>该套接字现在是不可继承的。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.fileno">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">fileno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.fileno" title="永久链接至目标">¶</a></dt>
<dd><p>返回套接字的文件描述符（一个小整数），失败返回 -1。配合 <a class="reference internal" href="select.html#select.select" title="select.select"><code class="xref py py-func docutils literal notranslate"><span class="pre">select.select()</span></code></a> 使用很有用。</p>
<p>在 Windows 下，此方法返回的小整数在允许使用文件描述符的地方无法使用（如 <a class="reference internal" href="os.html#os.fdopen" title="os.fdopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fdopen()</span></code></a> ）。Unix 无此限制。</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.get_inheritable">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">get_inheritable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.get_inheritable" title="永久链接至目标">¶</a></dt>
<dd><p>获取套接字文件描述符或套接字句柄的 <a class="reference internal" href="os.html#fd-inheritance"><span class="std std-ref">可继承标志</span></a> ：如果子进程可以继承套接字则为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，否则为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.4 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.getpeername">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">getpeername</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.getpeername" title="永久链接至目标">¶</a></dt>
<dd><p>返回套接字连接到的远程地址。举例而言，这可以用于查找远程 IPv4/v6 套接字的端口号。（返回的地址格式取决于地址簇 —— 参见上文。）部分系统不支持此函数。</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.getsockname">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">getsockname</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.getsockname" title="永久链接至目标">¶</a></dt>
<dd><p>返回套接字本身的地址。举例而言，这可以用于查找 IPv4/v6 套接字的端口号。（返回的地址格式取决于地址簇 —— 参见上文。）</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.getsockopt">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">getsockopt</code><span class="sig-paren">(</span><em class="sig-param">level</em>, <em class="sig-param">optname</em><span class="optional">[</span>, <em class="sig-param">buflen</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.getsockopt" title="永久链接至目标">¶</a></dt>
<dd><p>返回指定套接字选项的值（参阅 Unix 手册页 <em class="manpage">getsockopt(2)</em> ）。所需的符号常量（ <code class="xref py py-const docutils literal notranslate"><span class="pre">SO_*</span></code> 等）已定义在本模块中。如果未指定 <em>buflen</em>，则认为该选项值为整数，由本函数返回该整数值。如果指定 <em>buflen</em>，则它定义了用于存放选项值的缓冲区的最大长度，且该缓冲区将作为字节对象返回。对缓冲区的解码工作由调用者自行完成（针对编码为字节串的 C 结构，其解码方法请参阅可选的内置模块 <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> ）。</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.getblocking">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">getblocking</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.getblocking" title="永久链接至目标">¶</a></dt>
<dd><p>如果套接字处于阻塞模式，返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>，非阻塞模式返回 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
<p>这相当于检测 <code class="docutils literal notranslate"><span class="pre">socket.gettimeout()</span> <span class="pre">==</span> <span class="pre">0</span></code>。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.gettimeout">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">gettimeout</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.gettimeout" title="永久链接至目标">¶</a></dt>
<dd><p>返回套接字操作相关的超时秒数（浮点数），未设置超时则返回 <code class="docutils literal notranslate"><span class="pre">None</span></code>。它反映最后一次调用 <a class="reference internal" href="#socket.socket.setblocking" title="socket.socket.setblocking"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setblocking()</span></code></a> 或 <a class="reference internal" href="#socket.socket.settimeout" title="socket.socket.settimeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">settimeout()</span></code></a> 后的设置。</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.ioctl">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">ioctl</code><span class="sig-paren">(</span><em class="sig-param">control</em>, <em class="sig-param">option</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.ioctl" title="永久链接至目标">¶</a></dt>
<dd><dl class="field-list simple">
<dt class="field-odd">平台</dt>
<dd class="field-odd"><p>Windows</p>
</dd>
</dl>
<p><a class="reference internal" href="#socket.socket.ioctl" title="socket.socket.ioctl"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ioctl()</span></code></a> 方法是 WSAIoctl 系统接口的有限接口。请参考 <a class="reference external" href="https://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx">Win32 文档</a> 以获取更多信息。</p>
<p>在其他平台上，可以使用通用的 <a class="reference internal" href="fcntl.html#fcntl.fcntl" title="fcntl.fcntl"><code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl.fcntl()</span></code></a> 和 <a class="reference internal" href="fcntl.html#fcntl.ioctl" title="fcntl.ioctl"><code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl.ioctl()</span></code></a> 函数，它们接受套接字对象作为第一个参数。</p>
<p>当前仅支持以下控制码： <code class="docutils literal notranslate"><span class="pre">SIO_RCVALL</span></code>、<code class="docutils literal notranslate"><span class="pre">SIO_KEEPALIVE_VALS</span></code> 和 <code class="docutils literal notranslate"><span class="pre">SIO_LOOPBACK_FAST_PATH</span></code>。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.6 版更改: </span>添加了 <code class="docutils literal notranslate"><span class="pre">SIO_LOOPBACK_FAST_PATH</span></code>。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.listen">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">listen</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">backlog</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.listen" title="永久链接至目标">¶</a></dt>
<dd><p>启动一个服务器用于接受连接。如果指定 <em>backlog</em>，则它最低为 0（小于 0 会被置为 0），它指定系统允许暂未 accept 的连接数，超过后将拒绝新连接。未指定则自动设为合理的默认值。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span><em>backlog</em> 参数现在是可选的。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.makefile">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">makefile</code><span class="sig-paren">(</span><em class="sig-param">mode='r'</em>, <em class="sig-param">buffering=None</em>, <em class="sig-param">*</em>, <em class="sig-param">encoding=None</em>, <em class="sig-param">errors=None</em>, <em class="sig-param">newline=None</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.makefile" title="永久链接至目标">¶</a></dt>
<dd><p id="index-6">返回与套接字关联的 <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">文件对象</span></a>。返回的对象的具体类型取决于 <a class="reference internal" href="#socket.socket.makefile" title="socket.socket.makefile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">makefile()</span></code></a> 的参数。这些参数的解释方式与内置的 <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> 函数相同，其中 <em>mode</em> 的值仅支持 <code class="docutils literal notranslate"><span class="pre">'r'</span></code> （默认），<code class="docutils literal notranslate"><span class="pre">'w'</span></code> 和 <code class="docutils literal notranslate"><span class="pre">'b'</span></code>。</p>
<p>套接字必须处于阻塞模式，它可以有超时，但是如果发生超时，文件对象的内部缓冲区可能会以不一致的状态结尾。</p>
<p>关闭 <a class="reference internal" href="#socket.socket.makefile" title="socket.socket.makefile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">makefile()</span></code></a> 返回的文件对象不会关闭原始套接字，除非所有其他文件对象都已关闭且在套接字对象上调用了 <a class="reference internal" href="#socket.close" title="socket.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.close()</span></code></a>。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>在 Windows 上，由 <a class="reference internal" href="#socket.socket.makefile" title="socket.socket.makefile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">makefile()</span></code></a> 创建的文件类对象无法作为带文件描述符的文件对象使用，如无法作为 <a class="reference internal" href="subprocess.html#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-meth docutils literal notranslate"><span class="pre">subprocess.Popen()</span></code></a> 的流参数。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.recv">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">recv</code><span class="sig-paren">(</span><em class="sig-param">bufsize</em><span class="optional">[</span>, <em class="sig-param">flags</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.recv" title="永久链接至目标">¶</a></dt>
<dd><p>从套接字接收数据。返回值是一个字节对象，表示接收到的数据。<em>bufsize</em> 指定一次接收的最大数据量。可选参数 <em>flags</em> 的含义请参阅 Unix 手册页 <em class="manpage">recv(2)</em>，它默认为零。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>为了最佳匹配硬件和网络的实际情况，<em>bufsize</em> 的值应为 2 的相对较小的幂，如 4096。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 <a class="reference internal" href="exceptions.html#InterruptedError" title="InterruptedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterruptedError</span></code></a> 异常 (原因详见 <span class="target" id="index-34"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0475"><strong>PEP 475</strong></a>)。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.recvfrom">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">recvfrom</code><span class="sig-paren">(</span><em class="sig-param">bufsize</em><span class="optional">[</span>, <em class="sig-param">flags</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.recvfrom" title="永久链接至目标">¶</a></dt>
<dd><p>从套接字接收数据。返回值是一对 <code class="docutils literal notranslate"><span class="pre">(bytes,</span> <span class="pre">address)</span></code>，其中 <em>bytes</em> 是字节对象，表示接收到的数据，<em>address</em> 是发送端套接字的地址。可选参数 <em>flags</em> 的含义请参阅 Unix 手册页 <em class="manpage">recv(2)</em>，它默认为零。（ <em>address</em> 的格式取决于地址簇 —— 参见上文）</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 <a class="reference internal" href="exceptions.html#InterruptedError" title="InterruptedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterruptedError</span></code></a> 异常 (原因详见 <span class="target" id="index-35"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0475"><strong>PEP 475</strong></a>)。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>对于多播 IPv6 地址，<em>address</em> 的第一项不再包含 <code class="docutils literal notranslate"><span class="pre">%scope</span></code> 部分。要获得完整的 IPv6 地址，请使用 <a class="reference internal" href="#socket.getnameinfo" title="socket.getnameinfo"><code class="xref py py-func docutils literal notranslate"><span class="pre">getnameinfo()</span></code></a>。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.recvmsg">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">recvmsg</code><span class="sig-paren">(</span><em class="sig-param">bufsize</em><span class="optional">[</span>, <em class="sig-param">ancbufsize</em><span class="optional">[</span>, <em class="sig-param">flags</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.recvmsg" title="永久链接至目标">¶</a></dt>
<dd><p>从套接字接收普通数据（至多 <em>bufsize</em> 字节）和辅助数据。<em>ancbufsize</em> 参数设置用于接收辅助数据的内部缓冲区的大小（以字节为单位），默认为 0，表示不接收辅助数据。可以使用 <a class="reference internal" href="#socket.CMSG_SPACE" title="socket.CMSG_SPACE"><code class="xref py py-func docutils literal notranslate"><span class="pre">CMSG_SPACE()</span></code></a> 或 <a class="reference internal" href="#socket.CMSG_LEN" title="socket.CMSG_LEN"><code class="xref py py-func docutils literal notranslate"><span class="pre">CMSG_LEN()</span></code></a> 计算辅助数据缓冲区的合适大小，无法放入缓冲区的项目可能会被截断或丢弃。<em>flags</em> 参数默认为 0，其含义与 <a class="reference internal" href="#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a> 中的相同。</p>
<p>返回值是一个四元组： <code class="docutils literal notranslate"><span class="pre">(data,</span> <span class="pre">ancdata,</span> <span class="pre">msg_flags,</span> <span class="pre">address)</span></code>。<em>data</em> 项是一个 <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象，用于保存接收到的非辅助数据。<em>ancdata</em> 项是零个或多个元组 <code class="docutils literal notranslate"><span class="pre">(cmsg_level,</span> <span class="pre">cmsg_type,</span> <span class="pre">cmsg_data)</span></code> 组成的列表，表示接收到的辅助数据（控制消息）：<em>cmsg_level</em> 和 <em>cmsg_type</em> 是分别表示协议级别和协议类型的整数，而 <em>cmsg_data</em> 是保存相关数据的 <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象。<em>msg_flags</em> 项由各种标志按位或组成，表示接收消息的情况，详细信息请参阅系统文档。如果接收端套接字断开连接，则 <em>address</em> 是发送端套接字的地址（如果有），否则该值无指定。</p>
<p>某些系统上可以利用 <a class="reference internal" href="#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a> 套接字通过 <a class="reference internal" href="#socket.socket.sendmsg" title="socket.socket.sendmsg"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sendmsg()</span></code></a> 和 <a class="reference internal" href="#socket.socket.recvmsg" title="socket.socket.recvmsg"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recvmsg()</span></code></a> 在进程之间传递文件描述符。使用此功能时（通常仅限于 <a class="reference internal" href="#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a> 套接字），<a class="reference internal" href="#socket.socket.recvmsg" title="socket.socket.recvmsg"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recvmsg()</span></code></a> 将在其辅助数据中返回以下格式的项 <code class="docutils literal notranslate"><span class="pre">(socket.SOL_SOCKET,</span> <span class="pre">socket.SCM_RIGHTS,</span> <span class="pre">fds)</span></code>，其中 <em>fds</em> 是一个 <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象，是新文件描述符表示为原生 C <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> 类型的二进制数组。如果 <a class="reference internal" href="#socket.socket.recvmsg" title="socket.socket.recvmsg"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recvmsg()</span></code></a> 在系统调用返回后抛出异常，它将首先关闭此机制接收到的所有文件描述符。</p>
<p>对于仅接收到一部分的辅助数据项，一些系统没有指示其截断长度。如果某个项目可能超出了缓冲区的末尾，<a class="reference internal" href="#socket.socket.recvmsg" title="socket.socket.recvmsg"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recvmsg()</span></code></a> 将发出 <a class="reference internal" href="exceptions.html#RuntimeWarning" title="RuntimeWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeWarning</span></code></a>，并返回其在缓冲区内的部分，前提是该对象被截断于关联数据开始后。</p>
<p>在支持 <code class="xref py py-const docutils literal notranslate"><span class="pre">SCM_RIGHTS</span></code> 机制的系统上，下方的函数将最多接收 <em>maxfds</em> 个文件描述符，返回消息数据和包含描述符的列表（同时忽略意外情况，如接收到无关的控制消息）。另请参阅 <a class="reference internal" href="#socket.socket.sendmsg" title="socket.socket.sendmsg"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sendmsg()</span></code></a>。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">socket</span><span class="o">,</span> <span class="nn">array</span>

<span class="k">def</span> <span class="nf">recv_fds</span><span class="p">(</span><span class="n">sock</span><span class="p">,</span> <span class="n">msglen</span><span class="p">,</span> <span class="n">maxfds</span><span class="p">):</span>
    <span class="n">fds</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s2">&quot;i&quot;</span><span class="p">)</span>   <span class="c1"># Array of ints</span>
    <span class="n">msg</span><span class="p">,</span> <span class="n">ancdata</span><span class="p">,</span> <span class="n">flags</span><span class="p">,</span> <span class="n">addr</span> <span class="o">=</span> <span class="n">sock</span><span class="o">.</span><span class="n">recvmsg</span><span class="p">(</span><span class="n">msglen</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">CMSG_LEN</span><span class="p">(</span><span class="n">maxfds</span> <span class="o">*</span> <span class="n">fds</span><span class="o">.</span><span class="n">itemsize</span><span class="p">))</span>
    <span class="k">for</span> <span class="n">cmsg_level</span><span class="p">,</span> <span class="n">cmsg_type</span><span class="p">,</span> <span class="n">cmsg_data</span> <span class="ow">in</span> <span class="n">ancdata</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">cmsg_level</span> <span class="o">==</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOL_SOCKET</span> <span class="ow">and</span> <span class="n">cmsg_type</span> <span class="o">==</span> <span class="n">socket</span><span class="o">.</span><span class="n">SCM_RIGHTS</span><span class="p">:</span>
            <span class="c1"># Append data, ignoring any truncated integers at the end.</span>
            <span class="n">fds</span><span class="o">.</span><span class="n">frombytes</span><span class="p">(</span><span class="n">cmsg_data</span><span class="p">[:</span><span class="nb">len</span><span class="p">(</span><span class="n">cmsg_data</span><span class="p">)</span> <span class="o">-</span> <span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">cmsg_data</span><span class="p">)</span> <span class="o">%</span> <span class="n">fds</span><span class="o">.</span><span class="n">itemsize</span><span class="p">)])</span>
    <span class="k">return</span> <span class="n">msg</span><span class="p">,</span> <span class="nb">list</span><span class="p">(</span><span class="n">fds</span><span class="p">)</span>
</pre></div>
</div>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： 大多数 Unix 平台，其他平台也可能可用。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 <a class="reference internal" href="exceptions.html#InterruptedError" title="InterruptedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterruptedError</span></code></a> 异常 (原因详见 <span class="target" id="index-36"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0475"><strong>PEP 475</strong></a>)。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.recvmsg_into">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">recvmsg_into</code><span class="sig-paren">(</span><em class="sig-param">buffers</em><span class="optional">[</span>, <em class="sig-param">ancbufsize</em><span class="optional">[</span>, <em class="sig-param">flags</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.recvmsg_into" title="永久链接至目标">¶</a></dt>
<dd><p>从套接字接收普通数据和辅助数据，其行为与 <a class="reference internal" href="#socket.socket.recvmsg" title="socket.socket.recvmsg"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recvmsg()</span></code></a> 相同，但将非辅助数据分散到一系列缓冲区中，而不是返回新的字节对象。<em>buffers</em> 参数必须是可迭代对象，它迭代出可供写入的缓冲区（如 <a class="reference internal" href="stdtypes.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> 对象），这些缓冲区将被连续的非辅助数据块填充，直到数据全部写完或缓冲区用完为止。在允许使用的缓冲区数量上，操作系统可能会有限制（ <a class="reference internal" href="os.html#os.sysconf" title="os.sysconf"><code class="xref py py-func docutils literal notranslate"><span class="pre">sysconf()</span></code></a> 的 <code class="docutils literal notranslate"><span class="pre">SC_IOV_MAX</span></code> 值）。<em>ancbufsize</em> 和 <em>flags</em> 参数的含义与 <a class="reference internal" href="#socket.socket.recvmsg" title="socket.socket.recvmsg"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recvmsg()</span></code></a> 中的相同。</p>
<p>返回值为四元组： <code class="docutils literal notranslate"><span class="pre">(nbytes,</span> <span class="pre">ancdata,</span> <span class="pre">msg_flags,</span> <span class="pre">address)</span></code>，其中 <em>nbytes</em> 是写入缓冲区的非辅助数据的字节总数，而 <em>ancdata</em>、<em>msg_flags</em> 和 <em>address</em> 与 <a class="reference internal" href="#socket.socket.recvmsg" title="socket.socket.recvmsg"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recvmsg()</span></code></a> 中的相同。</p>
<p>示例:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">socket</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s1</span><span class="p">,</span> <span class="n">s2</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socketpair</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b1</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;----&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b2</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;0123456789&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b3</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;--------------&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s1</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;Mary had a little lamb&#39;</span><span class="p">)</span>
<span class="go">22</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s2</span><span class="o">.</span><span class="n">recvmsg_into</span><span class="p">([</span><span class="n">b1</span><span class="p">,</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">b2</span><span class="p">)[</span><span class="mi">2</span><span class="p">:</span><span class="mi">9</span><span class="p">],</span> <span class="n">b3</span><span class="p">])</span>
<span class="go">(22, [], 0, None)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">b1</span><span class="p">,</span> <span class="n">b2</span><span class="p">,</span> <span class="n">b3</span><span class="p">]</span>
<span class="go">[bytearray(b&#39;Mary&#39;), bytearray(b&#39;01 had a 9&#39;), bytearray(b&#39;little lamb---&#39;)]</span>
</pre></div>
</div>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： 大多数 Unix 平台，其他平台也可能可用。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.recvfrom_into">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">recvfrom_into</code><span class="sig-paren">(</span><em class="sig-param">buffer</em><span class="optional">[</span>, <em class="sig-param">nbytes</em><span class="optional">[</span>, <em class="sig-param">flags</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.recvfrom_into" title="永久链接至目标">¶</a></dt>
<dd><p>从套接字接收数据，将其写入 <em>buffer</em> 而不是创建新的字节串。返回值是一对 <code class="docutils literal notranslate"><span class="pre">(nbytes,</span> <span class="pre">address)</span></code>，其中 <em>nbytes</em> 是收到的字节数，<em>address</em> 是发送端套接字的地址。可选参数 <em>flags</em> 的含义请参阅 Unix 手册页 <em class="manpage">recv(2)</em>，它默认为零。（ <em>address</em> 的格式取决于地址簇 —— 参见上文）</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.recv_into">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">recv_into</code><span class="sig-paren">(</span><em class="sig-param">buffer</em><span class="optional">[</span>, <em class="sig-param">nbytes</em><span class="optional">[</span>, <em class="sig-param">flags</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.recv_into" title="永久链接至目标">¶</a></dt>
<dd><p>从套接字接收至多 <em>nbytes</em> 个字节，将其写入缓冲区而不是创建新的字节串。如果 <em>nbytes</em> 未指定（或指定为 0），则接收至所给缓冲区的最大可用大小。返回接收到的字节数。可选参数 <em>flags</em> 的含义请参阅 Unix 手册页 <em class="manpage">recv(2)</em>，它默认为零。</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.send">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">send</code><span class="sig-paren">(</span><em class="sig-param">bytes</em><span class="optional">[</span>, <em class="sig-param">flags</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.send" title="永久链接至目标">¶</a></dt>
<dd><p>发送数据给套接字。本套接字必须已连接到远程套接字。可选参数 <em>flags</em> 的含义与上述 <a class="reference internal" href="#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a> 中的相同。本方法返回已发送的字节数。应用程序要负责检查所有数据是否已发送，如果仅传输了部分数据，程序需要自行尝试传输其余数据。有关该主题的更多信息，请参考 <a class="reference internal" href="../howto/sockets.html#socket-howto"><span class="std std-ref">套接字编程指南</span></a>。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 <a class="reference internal" href="exceptions.html#InterruptedError" title="InterruptedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterruptedError</span></code></a> 异常 (原因详见 <span class="target" id="index-37"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0475"><strong>PEP 475</strong></a>)。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.sendall">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">sendall</code><span class="sig-paren">(</span><em class="sig-param">bytes</em><span class="optional">[</span>, <em class="sig-param">flags</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.sendall" title="永久链接至目标">¶</a></dt>
<dd><p>发送数据给套接字。本套接字必须已连接到远程套接字。可选参数 <em>flags</em> 的含义与上述 <a class="reference internal" href="#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a> 中的相同。与 <a class="reference internal" href="#socket.socket.send" title="socket.socket.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> 不同，本方法持续从 <em>bytes</em> 发送数据，直到所有数据都已发送或发生错误为止。成功后会返回 <code class="docutils literal notranslate"><span class="pre">None</span></code>。出错后会抛出一个异常，此时并没有办法确定成功发送了多少数据。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>每次成功发送数据后，套接字超时不再重置。现在，套接字超时是发送所有数据的最大总持续时间。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 <a class="reference internal" href="exceptions.html#InterruptedError" title="InterruptedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterruptedError</span></code></a> 异常 (原因详见 <span class="target" id="index-38"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0475"><strong>PEP 475</strong></a>)。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.sendto">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">sendto</code><span class="sig-paren">(</span><em class="sig-param">bytes</em>, <em class="sig-param">address</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.sendto" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">sendto</code><span class="sig-paren">(</span><em class="sig-param">bytes</em>, <em class="sig-param">flags</em>, <em class="sig-param">address</em><span class="sig-paren">)</span></dt>
<dd><p>发送数据给套接字。本套接字不应连接到远程套接字，而应由 <em>address</em> 指定目标套接字。可选参数 <em>flags</em> 的含义与上述 <a class="reference internal" href="#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a> 中的相同。本方法返回已发送的字节数。（ <em>address</em> 的格式取决于地址簇 —— 参见上文。）</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 <a class="reference internal" href="exceptions.html#InterruptedError" title="InterruptedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterruptedError</span></code></a> 异常 (原因详见 <span class="target" id="index-39"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0475"><strong>PEP 475</strong></a>)。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.sendmsg">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">sendmsg</code><span class="sig-paren">(</span><em class="sig-param">buffers</em><span class="optional">[</span>, <em class="sig-param">ancdata</em><span class="optional">[</span>, <em class="sig-param">flags</em><span class="optional">[</span>, <em class="sig-param">address</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.sendmsg" title="永久链接至目标">¶</a></dt>
<dd><p>将普通数据和辅助数据发送给套接字，将从一系列缓冲区中收集非辅助数据，并将其拼接为一条消息。<em>buffers</em> 参数指定的非辅助数据应为可迭代的 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">字节类对象</span></a> （如 <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象），在允许使用的缓冲区数量上，操作系统可能会有限制（ <a class="reference internal" href="os.html#os.sysconf" title="os.sysconf"><code class="xref py py-func docutils literal notranslate"><span class="pre">sysconf()</span></code></a> 的 <code class="docutils literal notranslate"><span class="pre">SC_IOV_MAX</span></code> 值）。<em>ancdata</em> 参数指定的辅助数据（控制消息）应为可迭代对象，迭代出零个或多个 <code class="docutils literal notranslate"><span class="pre">(cmsg_level,</span> <span class="pre">cmsg_type,</span> <span class="pre">cmsg_data)</span></code> 元组，其中 <em>cmsg_level</em> 和 <em>cmsg_type</em> 是分别指定协议级别和协议类型的整数，而 <em>cmsg_data</em> 是保存相关数据的字节类对象。请注意，某些系统（特别是没有 <a class="reference internal" href="#socket.CMSG_SPACE" title="socket.CMSG_SPACE"><code class="xref py py-func docutils literal notranslate"><span class="pre">CMSG_SPACE()</span></code></a> 的系统）可能每次调用仅支持发送一条控制消息。<em>flags</em> 参数默认为 0，与 <a class="reference internal" href="#socket.socket.send" title="socket.socket.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> 中的含义相同。如果 <em>address</em> 指定为除 <code class="docutils literal notranslate"><span class="pre">None</span></code> 以外的值，它将作为消息的目标地址。返回值是已发送的非辅助数据的字节数。</p>
<p>在支持 <code class="xref py py-const docutils literal notranslate"><span class="pre">SCM_RIGHTS</span></code> 机制的系统上，下方的函数通过一个 <a class="reference internal" href="#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a> 套接字来发送文件描述符列表 <em>fds</em>。另请参阅 <a class="reference internal" href="#socket.socket.recvmsg" title="socket.socket.recvmsg"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recvmsg()</span></code></a>。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">socket</span><span class="o">,</span> <span class="nn">array</span>

<span class="k">def</span> <span class="nf">send_fds</span><span class="p">(</span><span class="n">sock</span><span class="p">,</span> <span class="n">msg</span><span class="p">,</span> <span class="n">fds</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">sock</span><span class="o">.</span><span class="n">sendmsg</span><span class="p">([</span><span class="n">msg</span><span class="p">],</span> <span class="p">[(</span><span class="n">socket</span><span class="o">.</span><span class="n">SOL_SOCKET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SCM_RIGHTS</span><span class="p">,</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s2">&quot;i&quot;</span><span class="p">,</span> <span class="n">fds</span><span class="p">))])</span>
</pre></div>
</div>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： 大多数 Unix 平台，其他平台也可能可用。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 <a class="reference internal" href="exceptions.html#InterruptedError" title="InterruptedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterruptedError</span></code></a> 异常 (原因详见 <span class="target" id="index-40"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0475"><strong>PEP 475</strong></a>)。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.sendmsg_afalg">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">sendmsg_afalg</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">msg</em>, <span class="optional">]</span><em class="sig-param">*</em>, <em class="sig-param">op</em><span class="optional">[</span>, <em class="sig-param">iv</em><span class="optional">[</span>, <em class="sig-param">assoclen</em><span class="optional">[</span>, <em class="sig-param">flags</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.sendmsg_afalg" title="永久链接至目标">¶</a></dt>
<dd><p>为 <a class="reference internal" href="#socket.AF_ALG" title="socket.AF_ALG"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_ALG</span></code></a> 套接字定制的 <a class="reference internal" href="#socket.socket.sendmsg" title="socket.socket.sendmsg"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sendmsg()</span></code></a> 版本。可为 <a class="reference internal" href="#socket.AF_ALG" title="socket.AF_ALG"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_ALG</span></code></a> 套接字设置模式、IV、AEAD 关联数据的长度和标志位。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>： Linux &gt;= 2.6.38。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.6 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.sendfile">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">sendfile</code><span class="sig-paren">(</span><em class="sig-param">file</em>, <em class="sig-param">offset=0</em>, <em class="sig-param">count=None</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.sendfile" title="永久链接至目标">¶</a></dt>
<dd><p>使用高性能的 <a class="reference internal" href="os.html#os.sendfile" title="os.sendfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.sendfile</span></code></a> 发送文件，直到达到文件的 EOF 为止，返回已发送的字节总数。<em>file</em> 必须是一个以二进制模式打开的常规文件对象。如果 <a class="reference internal" href="os.html#os.sendfile" title="os.sendfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.sendfile</span></code></a> 不可用（如 Windows）或 <em>file</em> 不是常规文件，将使用 <a class="reference internal" href="#socket.socket.send" title="socket.socket.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> 代替。<em>offset</em> 指示从哪里开始读取文件。如果指定了 <em>count</em>，它确定了要发送的字节总数，而不会持续发送直到达到文件的 EOF。返回时或发生错误时，文件位置将更新，在这种情况下，<a class="reference internal" href="io.html#io.IOBase.tell" title="io.IOBase.tell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">file.tell()</span></code></a> 可用于确定已发送的字节数。套接字必须为 <a class="reference internal" href="#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a> 类型。不支持非阻塞的套接字。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.5 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.set_inheritable">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">set_inheritable</code><span class="sig-paren">(</span><em class="sig-param">inheritable</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.set_inheritable" title="永久链接至目标">¶</a></dt>
<dd><p>设置套接字文件描述符或套接字句柄的 <a class="reference internal" href="os.html#fd-inheritance"><span class="std std-ref">可继承标志</span></a>。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.4 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.setblocking">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">setblocking</code><span class="sig-paren">(</span><em class="sig-param">flag</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.setblocking" title="永久链接至目标">¶</a></dt>
<dd><p>设置套接字为阻塞或非阻塞模式：如果 <em>flag</em> 为 false，则将套接字设置为非阻塞，否则设置为阻塞。</p>
<p>本方法是某些 <a class="reference internal" href="#socket.socket.settimeout" title="socket.socket.settimeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">settimeout()</span></code></a> 调用的简写：</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">sock.setblocking(True)</span></code> 相当于 <code class="docutils literal notranslate"><span class="pre">sock.settimeout(None)</span></code></p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">sock.setblocking(False)</span></code> 相当于 <code class="docutils literal notranslate"><span class="pre">sock.settimeout(0.0)</span></code></p></li>
</ul>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>本方法不再对 <a class="reference internal" href="#socket.socket.type" title="socket.socket.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">socket.type</span></code></a> 属性设置 <a class="reference internal" href="#socket.SOCK_NONBLOCK" title="socket.SOCK_NONBLOCK"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_NONBLOCK</span></code></a> 标志。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.settimeout">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">settimeout</code><span class="sig-paren">(</span><em class="sig-param">value</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.settimeout" title="永久链接至目标">¶</a></dt>
<dd><p>为阻塞套接字的操作设置超时。<em>value</em> 参数可以是非负浮点数，表示秒，也可以是 <code class="docutils literal notranslate"><span class="pre">None</span></code>。如果赋为一个非零值，那么如果在操作完成前超过了超时时间 <em>value</em>，后续的套接字操作将抛出 <a class="reference internal" href="#socket.timeout" title="socket.timeout"><code class="xref py py-exc docutils literal notranslate"><span class="pre">timeout</span></code></a> 异常。如果赋为 0，则套接字将处于非阻塞模式。如果指定为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则套接字将处于阻塞模式。</p>
<p>更多信息请查阅 <a class="reference internal" href="#socket-timeouts"><span class="std std-ref">关于套接字超时的说明</span></a>。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>本方法不再修改 <a class="reference internal" href="#socket.socket.type" title="socket.socket.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">socket.type</span></code></a> 属性的 <a class="reference internal" href="#socket.SOCK_NONBLOCK" title="socket.SOCK_NONBLOCK"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_NONBLOCK</span></code></a> 标志。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.setsockopt">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">setsockopt</code><span class="sig-paren">(</span><em class="sig-param">level</em>, <em class="sig-param">optname</em>, <em class="sig-param">value: int</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.setsockopt" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<dl class="method">
<dt>
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">setsockopt</code><span class="sig-paren">(</span><em class="sig-param">level</em>, <em class="sig-param">optname</em>, <em class="sig-param">value: buffer</em><span class="sig-paren">)</span></dt>
<dd></dd></dl>

<dl class="method">
<dt>
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">setsockopt</code><span class="sig-paren">(</span><em class="sig-param">level</em>, <em class="sig-param">optname</em>, <em class="sig-param">None</em>, <em class="sig-param">optlen: int</em><span class="sig-paren">)</span></dt>
<dd><p id="index-14">设置给定套接字选项的值（参阅 Unix 手册页 <em class="manpage">setsockopt(2)</em> ）。所需的符号常量（ <code class="xref py py-const docutils literal notranslate"><span class="pre">SO_*</span></code> 等）已定义在本 <a class="reference internal" href="#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> 模块中。该值可以是整数、<code class="docutils literal notranslate"><span class="pre">None</span></code> 或表示缓冲区的 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">字节类对象</span></a>。在后一种情况下，由调用者确保字节串中包含正确的数据位（关于将 C 结构体编码为字节串的方法，请参阅可选的内置模块 <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> ）。当 <em>value</em> 设置为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 时，必须设置 <em>optlen</em> 参数。这相当于调用 <code class="xref c c-func docutils literal notranslate"><span class="pre">setsockopt()</span></code> C 函数时使用了 <code class="docutils literal notranslate"><span class="pre">optval=NULL</span></code> 和 <code class="docutils literal notranslate"><span class="pre">optlen=optlen</span></code> 参数。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>现在支持可写的 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">字节类对象</span></a>。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.6 版更改: </span>添加了 setsockopt(level, optname, None, optlen: int) 调用形式。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.shutdown">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">shutdown</code><span class="sig-paren">(</span><em class="sig-param">how</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.shutdown" title="永久链接至目标">¶</a></dt>
<dd><p>关闭一半或全部的连接。如果 <em>how</em> 为 <code class="xref py py-const docutils literal notranslate"><span class="pre">SHUT_RD</span></code>，则后续不再允许接收。如果 <em>how</em> 为 <code class="xref py py-const docutils literal notranslate"><span class="pre">SHUT_WR</span></code>，则后续不再允许发送。如果 <em>how</em> 为 <code class="xref py py-const docutils literal notranslate"><span class="pre">SHUT_RDWR</span></code>，则后续的发送和接收都不允许。</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.share">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">share</code><span class="sig-paren">(</span><em class="sig-param">process_id</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.share" title="永久链接至目标">¶</a></dt>
<dd><p>复制套接字，并准备将其与目标进程共享。目标进程必须以 <em>process_id</em> 形式提供。然后可以利用某种形式的进程间通信，将返回的字节对象传递给目标进程，还可以使用 <a class="reference internal" href="#socket.fromshare" title="socket.fromshare"><code class="xref py py-func docutils literal notranslate"><span class="pre">fromshare()</span></code></a> 在新进程中重新创建套接字。一旦本方法调用完毕，就可以安全地将套接字关闭，因为操作系统已经为目标进程复制了该套接字。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>: Windows。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<p>注意此处没有 <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> 或 <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> 方法，请使用不带 <em>flags</em> 参数的 <a class="reference internal" href="#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a> 和 <a class="reference internal" href="#socket.socket.send" title="socket.socket.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> 来替代。</p>
<p>套接字对象还具有以下（只读）属性，这些属性与传入 <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket</span></code></a> 构造函数的值相对应。</p>
<dl class="attribute">
<dt id="socket.socket.family">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">family</code><a class="headerlink" href="#socket.socket.family" title="永久链接至目标">¶</a></dt>
<dd><p>套接字的协议簇</p>
</dd></dl>

<dl class="attribute">
<dt id="socket.socket.type">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">type</code><a class="headerlink" href="#socket.socket.type" title="永久链接至目标">¶</a></dt>
<dd><p>套接字的类型</p>
</dd></dl>

<dl class="attribute">
<dt id="socket.socket.proto">
<code class="sig-prename descclassname">socket.</code><code class="sig-name descname">proto</code><a class="headerlink" href="#socket.socket.proto" title="永久链接至目标">¶</a></dt>
<dd><p>套接字的协议。</p>
</dd></dl>

</div>
<div class="section" id="notes-on-socket-timeouts">
<span id="socket-timeouts"></span><h2>关于套接字超时的说明<a class="headerlink" href="#notes-on-socket-timeouts" title="永久链接至标题">¶</a></h2>
<p>一个套接字对象可以处于以下三种模式之一：阻塞、非阻塞或超时。套接字默认以阻塞模式创建，但是可以调用 <a class="reference internal" href="#socket.setdefaulttimeout" title="socket.setdefaulttimeout"><code class="xref py py-func docutils literal notranslate"><span class="pre">setdefaulttimeout()</span></code></a> 来更改。</p>
<ul class="simple">
<li><p>在 <em>blocking mode</em> （阻塞模式）中，操作将阻塞，直到操作完成或系统返回错误（如连接超时）。</p></li>
<li><p>在 <em>non-blocking mode</em> （非阻塞模式）中，如果操作无法立即完成，则操作将失败（不幸的是，不同系统返回的错误不同）：位于 <a class="reference internal" href="select.html#module-select" title="select: Wait for I/O completion on multiple streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">select</span></code></a> 中的函数可用于了解套接字何时以及是否可以读取或写入。</p></li>
<li><p>在 <em>timeout mode</em> （超时模式）下，如果无法在指定的超时内完成操作（抛出 <a class="reference internal" href="#socket.timeout" title="socket.timeout"><code class="xref py py-exc docutils literal notranslate"><span class="pre">timeout</span></code></a> 异常），或如果系统返回错误，则操作将失败。</p></li>
</ul>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>在操作系统层面上，<em>超时模式</em> 下的套接字在内部都设置为非阻塞模式。同时，阻塞和超时模式在文件描述符和套接字对象之间共享，这些描述符和对象均应指向同一个网络端点。如果，比如你决定使用套接字的 <a class="reference internal" href="#socket.socket.fileno" title="socket.socket.fileno"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code></a>，这一实现细节可能导致明显的结果。</p>
</div>
<div class="section" id="timeouts-and-the-connect-method">
<h3>超时与 <code class="docutils literal notranslate"><span class="pre">connect</span></code> 方法<a class="headerlink" href="#timeouts-and-the-connect-method" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#socket.socket.connect" title="socket.socket.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code></a> 操作也受超时设置的约束，通常建议在调用 <a class="reference internal" href="#socket.socket.connect" title="socket.socket.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code></a> 之前调用 <a class="reference internal" href="#socket.socket.settimeout" title="socket.socket.settimeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">settimeout()</span></code></a>，或将超时参数直接传递给 <a class="reference internal" href="#socket.create_connection" title="socket.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">create_connection()</span></code></a>。但是，无论 Python 套接字超时设置如何，系统网络栈都有可能返回自带的连接超时错误。</p>
</div>
<div class="section" id="timeouts-and-the-accept-method">
<h3>超时与 <code class="docutils literal notranslate"><span class="pre">accept</span></code> 方法<a class="headerlink" href="#timeouts-and-the-accept-method" title="永久链接至标题">¶</a></h3>
<p>如果 <a class="reference internal" href="#socket.getdefaulttimeout" title="socket.getdefaulttimeout"><code class="xref py py-func docutils literal notranslate"><span class="pre">getdefaulttimeout()</span></code></a> 的值不是 <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>，则 <a class="reference internal" href="#socket.socket.accept" title="socket.socket.accept"><code class="xref py py-meth docutils literal notranslate"><span class="pre">accept()</span></code></a> 方法返回的套接字将继承该超时值。若是 None，返回的套接字行为取决于侦听套接字的设置：</p>
<ul class="simple">
<li><p>如果侦听套接字处于 <em>阻塞模式</em> 或 <em>超时模式</em>，则 <a class="reference internal" href="#socket.socket.accept" title="socket.socket.accept"><code class="xref py py-meth docutils literal notranslate"><span class="pre">accept()</span></code></a> 返回的套接字处于 <em>阻塞模式</em>；</p></li>
<li><p>如果侦听套接字处于 <em>非阻塞模式</em>，那么 <a class="reference internal" href="#socket.socket.accept" title="socket.socket.accept"><code class="xref py py-meth docutils literal notranslate"><span class="pre">accept()</span></code></a> 返回的套接字是阻塞还是非阻塞取决于操作系统。如果要确保跨平台时的正确行为，建议手动覆盖此设置。</p></li>
</ul>
</div>
</div>
<div class="section" id="example">
<span id="socket-example"></span><h2>示例<a class="headerlink" href="#example" title="永久链接至标题">¶</a></h2>
<p>以下是 4 个使用 TCP/IP 协议的最小示例程序：一台服务器，它将收到的所有数据原样返回（仅服务于一个客户端），还有一个使用该服务器的客户端。注意，服务器必须按序执行 <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a>, <a class="reference internal" href="#socket.socket.bind" title="socket.socket.bind"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bind()</span></code></a>, <a class="reference internal" href="#socket.socket.listen" title="socket.socket.listen"><code class="xref py py-meth docutils literal notranslate"><span class="pre">listen()</span></code></a>, <a class="reference internal" href="#socket.socket.accept" title="socket.socket.accept"><code class="xref py py-meth docutils literal notranslate"><span class="pre">accept()</span></code></a> （可能需要重复执行 <a class="reference internal" href="#socket.socket.accept" title="socket.socket.accept"><code class="xref py py-meth docutils literal notranslate"><span class="pre">accept()</span></code></a> 以服务多个客户端），而客户端仅需要按序执行 <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a>, <a class="reference internal" href="#socket.socket.connect" title="socket.socket.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code></a>。还须注意，服务器不在侦听套接字上发送 <a class="reference internal" href="#socket.socket.sendall" title="socket.socket.sendall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sendall()</span></code></a>/<a class="reference internal" href="#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a>，而是在 <a class="reference internal" href="#socket.socket.accept" title="socket.socket.accept"><code class="xref py py-meth docutils literal notranslate"><span class="pre">accept()</span></code></a> 返回的新套接字上发送。</p>
<p>前两个示例仅支持 IPv4。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Echo server program</span>
<span class="kn">import</span> <span class="nn">socket</span>

<span class="n">HOST</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>                 <span class="c1"># Symbolic name meaning all available interfaces</span>
<span class="n">PORT</span> <span class="o">=</span> <span class="mi">50007</span>              <span class="c1"># Arbitrary non-privileged port</span>
<span class="k">with</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span> <span class="k">as</span> <span class="n">s</span><span class="p">:</span>
    <span class="n">s</span><span class="o">.</span><span class="n">bind</span><span class="p">((</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">))</span>
    <span class="n">s</span><span class="o">.</span><span class="n">listen</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
    <span class="n">conn</span><span class="p">,</span> <span class="n">addr</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">accept</span><span class="p">()</span>
    <span class="k">with</span> <span class="n">conn</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Connected by&#39;</span><span class="p">,</span> <span class="n">addr</span><span class="p">)</span>
        <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
            <span class="n">data</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="n">data</span><span class="p">:</span> <span class="k">break</span>
            <span class="n">conn</span><span class="o">.</span><span class="n">sendall</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
</pre></div>
</div>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Echo client program</span>
<span class="kn">import</span> <span class="nn">socket</span>

<span class="n">HOST</span> <span class="o">=</span> <span class="s1">&#39;daring.cwi.nl&#39;</span>    <span class="c1"># The remote host</span>
<span class="n">PORT</span> <span class="o">=</span> <span class="mi">50007</span>              <span class="c1"># The same port as used by the server</span>
<span class="k">with</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span> <span class="k">as</span> <span class="n">s</span><span class="p">:</span>
    <span class="n">s</span><span class="o">.</span><span class="n">connect</span><span class="p">((</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">))</span>
    <span class="n">s</span><span class="o">.</span><span class="n">sendall</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;Hello, world&#39;</span><span class="p">)</span>
    <span class="n">data</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Received&#39;</span><span class="p">,</span> <span class="nb">repr</span><span class="p">(</span><span class="n">data</span><span class="p">))</span>
</pre></div>
</div>
<p>下两个例子与上两个很像，但是同时支持 IPv4 和 IPv6。 服务端将监听第一个可用的地址族（它本应同时监听两个）。 在大多数支持 IPv6 的系统上，IPv6 将有优先权并且服务端可能不会接受 IPv4 流量。 客户端将尝试连接到作为名称解析结果被返回的所有地址，并将流量发送给连接成功的第一个地址。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Echo server program</span>
<span class="kn">import</span> <span class="nn">socket</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="n">HOST</span> <span class="o">=</span> <span class="kc">None</span>               <span class="c1"># Symbolic name meaning all available interfaces</span>
<span class="n">PORT</span> <span class="o">=</span> <span class="mi">50007</span>              <span class="c1"># Arbitrary non-privileged port</span>
<span class="n">s</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">for</span> <span class="n">res</span> <span class="ow">in</span> <span class="n">socket</span><span class="o">.</span><span class="n">getaddrinfo</span><span class="p">(</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">AF_UNSPEC</span><span class="p">,</span>
                              <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">AI_PASSIVE</span><span class="p">):</span>
    <span class="n">af</span><span class="p">,</span> <span class="n">socktype</span><span class="p">,</span> <span class="n">proto</span><span class="p">,</span> <span class="n">canonname</span><span class="p">,</span> <span class="n">sa</span> <span class="o">=</span> <span class="n">res</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">af</span><span class="p">,</span> <span class="n">socktype</span><span class="p">,</span> <span class="n">proto</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">OSError</span> <span class="k">as</span> <span class="n">msg</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="k">continue</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">s</span><span class="o">.</span><span class="n">bind</span><span class="p">(</span><span class="n">sa</span><span class="p">)</span>
        <span class="n">s</span><span class="o">.</span><span class="n">listen</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">OSError</span> <span class="k">as</span> <span class="n">msg</span><span class="p">:</span>
        <span class="n">s</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="n">s</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="k">continue</span>
    <span class="k">break</span>
<span class="k">if</span> <span class="n">s</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;could not open socket&#39;</span><span class="p">)</span>
    <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">conn</span><span class="p">,</span> <span class="n">addr</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">accept</span><span class="p">()</span>
<span class="k">with</span> <span class="n">conn</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Connected by&#39;</span><span class="p">,</span> <span class="n">addr</span><span class="p">)</span>
    <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
        <span class="n">data</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">data</span><span class="p">:</span> <span class="k">break</span>
        <span class="n">conn</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
</pre></div>
</div>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Echo client program</span>
<span class="kn">import</span> <span class="nn">socket</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="n">HOST</span> <span class="o">=</span> <span class="s1">&#39;daring.cwi.nl&#39;</span>    <span class="c1"># The remote host</span>
<span class="n">PORT</span> <span class="o">=</span> <span class="mi">50007</span>              <span class="c1"># The same port as used by the server</span>
<span class="n">s</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">for</span> <span class="n">res</span> <span class="ow">in</span> <span class="n">socket</span><span class="o">.</span><span class="n">getaddrinfo</span><span class="p">(</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">AF_UNSPEC</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">):</span>
    <span class="n">af</span><span class="p">,</span> <span class="n">socktype</span><span class="p">,</span> <span class="n">proto</span><span class="p">,</span> <span class="n">canonname</span><span class="p">,</span> <span class="n">sa</span> <span class="o">=</span> <span class="n">res</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">af</span><span class="p">,</span> <span class="n">socktype</span><span class="p">,</span> <span class="n">proto</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">OSError</span> <span class="k">as</span> <span class="n">msg</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="k">continue</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">s</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">sa</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">OSError</span> <span class="k">as</span> <span class="n">msg</span><span class="p">:</span>
        <span class="n">s</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="n">s</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="k">continue</span>
    <span class="k">break</span>
<span class="k">if</span> <span class="n">s</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;could not open socket&#39;</span><span class="p">)</span>
    <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="k">with</span> <span class="n">s</span><span class="p">:</span>
    <span class="n">s</span><span class="o">.</span><span class="n">sendall</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;Hello, world&#39;</span><span class="p">)</span>
    <span class="n">data</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Received&#39;</span><span class="p">,</span> <span class="nb">repr</span><span class="p">(</span><span class="n">data</span><span class="p">))</span>
</pre></div>
</div>
<p>下面的例子演示了如何在 Windows 上使用原始套接字编写一个非常简单的网络嗅探器。 这个例子需要管理员权限来修改接口:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">socket</span>

<span class="c1"># the public network interface</span>
<span class="n">HOST</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">gethostbyname</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">gethostname</span><span class="p">())</span>

<span class="c1"># create a raw socket and bind it to the public interface</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_RAW</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">IPPROTO_IP</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">bind</span><span class="p">((</span><span class="n">HOST</span><span class="p">,</span> <span class="mi">0</span><span class="p">))</span>

<span class="c1"># Include IP headers</span>
<span class="n">s</span><span class="o">.</span><span class="n">setsockopt</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">IPPROTO_IP</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">IP_HDRINCL</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>

<span class="c1"># receive all packages</span>
<span class="n">s</span><span class="o">.</span><span class="n">ioctl</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">SIO_RCVALL</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">RCVALL_ON</span><span class="p">)</span>

<span class="c1"># receive a package</span>
<span class="nb">print</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">recvfrom</span><span class="p">(</span><span class="mi">65565</span><span class="p">))</span>

<span class="c1"># disabled promiscuous mode</span>
<span class="n">s</span><span class="o">.</span><span class="n">ioctl</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">SIO_RCVALL</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">RCVALL_OFF</span><span class="p">)</span>
</pre></div>
</div>
<p>下面的例子演示了如何使用 socket 接口与采用原始套接字协议的 CAN 网络进行通信。 要改为通过广播管理器协议来使用 CAN，则要用以下方式打开一个 socket:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_CAN</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_DGRAM</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">CAN_BCM</span><span class="p">)</span>
</pre></div>
</div>
<p>在绑定 (<code class="xref py py-const docutils literal notranslate"><span class="pre">CAN_RAW</span></code>) 或连接 (<a class="reference internal" href="#socket.CAN_BCM" title="socket.CAN_BCM"><code class="xref py py-const docutils literal notranslate"><span class="pre">CAN_BCM</span></code></a>) socket 之后，你将可以在 socket 对象上正常使用 <a class="reference internal" href="#socket.socket.send" title="socket.socket.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.send()</span></code></a> 以及 <a class="reference internal" href="#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.recv()</span></code></a> 操作（及同类操作）。</p>
<p>最后一个例子可能需要特别的权限:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">socket</span>
<span class="kn">import</span> <span class="nn">struct</span>


<span class="c1"># CAN frame packing/unpacking (see &#39;struct can_frame&#39; in &lt;linux/can.h&gt;)</span>

<span class="n">can_frame_fmt</span> <span class="o">=</span> <span class="s2">&quot;=IB3x8s&quot;</span>
<span class="n">can_frame_size</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">calcsize</span><span class="p">(</span><span class="n">can_frame_fmt</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">build_can_frame</span><span class="p">(</span><span class="n">can_id</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
    <span class="n">can_dlc</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
    <span class="n">data</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">ljust</span><span class="p">(</span><span class="mi">8</span><span class="p">,</span> <span class="sa">b</span><span class="s1">&#39;</span><span class="se">\x00</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">struct</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="n">can_frame_fmt</span><span class="p">,</span> <span class="n">can_id</span><span class="p">,</span> <span class="n">can_dlc</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">dissect_can_frame</span><span class="p">(</span><span class="n">frame</span><span class="p">):</span>
    <span class="n">can_id</span><span class="p">,</span> <span class="n">can_dlc</span><span class="p">,</span> <span class="n">data</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">unpack</span><span class="p">(</span><span class="n">can_frame_fmt</span><span class="p">,</span> <span class="n">frame</span><span class="p">)</span>
    <span class="k">return</span> <span class="p">(</span><span class="n">can_id</span><span class="p">,</span> <span class="n">can_dlc</span><span class="p">,</span> <span class="n">data</span><span class="p">[:</span><span class="n">can_dlc</span><span class="p">])</span>


<span class="c1"># create a raw socket and bind it to the &#39;vcan0&#39; interface</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_CAN</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_RAW</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">CAN_RAW</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">bind</span><span class="p">((</span><span class="s1">&#39;vcan0&#39;</span><span class="p">,))</span>

<span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
    <span class="n">cf</span><span class="p">,</span> <span class="n">addr</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">recvfrom</span><span class="p">(</span><span class="n">can_frame_size</span><span class="p">)</span>

    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Received: can_id=</span><span class="si">%x</span><span class="s1">, can_dlc=</span><span class="si">%x</span><span class="s1">, data=</span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">dissect_can_frame</span><span class="p">(</span><span class="n">cf</span><span class="p">))</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="n">s</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">cf</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">OSError</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Error sending CAN frame&#39;</span><span class="p">)</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="n">s</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">build_can_frame</span><span class="p">(</span><span class="mh">0x01</span><span class="p">,</span> <span class="sa">b</span><span class="s1">&#39;</span><span class="se">\x01\x02\x03</span><span class="s1">&#39;</span><span class="p">))</span>
    <span class="k">except</span> <span class="ne">OSError</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Error sending CAN frame&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>如果多次运行示例，且两次运行间隔很短，可能引发此错误:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="ne">OSError</span><span class="p">:</span> <span class="p">[</span><span class="n">Errno</span> <span class="mi">98</span><span class="p">]</span> <span class="n">Address</span> <span class="n">already</span> <span class="ow">in</span> <span class="n">use</span>
</pre></div>
</div>
<p>这是因为前一次运行使套接字处于 <code class="docutils literal notranslate"><span class="pre">TIME_WAIT</span></code> 状态，无法立即重用。</p>
<p>要防止这种情况，需要设置一个 <a class="reference internal" href="#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> 标志 <code class="xref py py-data docutils literal notranslate"><span class="pre">socket.SO_REUSEADDR</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">setsockopt</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">SOL_SOCKET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SO_REUSEADDR</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">bind</span><span class="p">((</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">))</span>
</pre></div>
</div>
<p><code class="xref py py-data docutils literal notranslate"><span class="pre">SO_REUSEADDR</span></code> 标志告诉内核将处于 <code class="docutils literal notranslate"><span class="pre">TIME_WAIT</span></code> 状态的本地套接字重新使用，而不必等到固有的超时到期。</p>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p>关于套接字编程（C 语言）的介绍，请参阅以下文章：</p>
<ul class="simple">
<li><p><em>An Introductory 4.3BSD Interprocess Communication Tutorial</em>，作者 Stuart Sechrest</p></li>
<li><p><em>An Advanced 4.3BSD Interprocess Communication Tutorial</em>，作者 Samuel J.  Leffler et al,</p></li>
</ul>
<p>两篇文章都在 UNIX 开发者手册，补充文档 1（第 PS1:7 和 PS1:8 节）中。那些特定于平台的参考资料，它们包含与套接字有关的各种系统调用，也是套接字语义细节的宝贵信息来源。对于 Unix，请参考手册页。对于 Windows，请参阅 WinSock（或 Winsock 2）规范。如果需要支持 IPv6 的 API，读者可能希望参考 <span class="target" id="index-41"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3493.html"><strong>RFC 3493</strong></a>，标题为 Basic Socket Interface Extensions for IPv6。</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">目录</a></h3>
  <ul>
<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code> --- 底层网络接口</a><ul>
<li><a class="reference internal" href="#socket-families">套接字协议族</a></li>
<li><a class="reference internal" href="#module-contents">模块内容</a><ul>
<li><a class="reference internal" href="#exceptions">异常</a></li>
<li><a class="reference internal" href="#constants">常量</a></li>
<li><a class="reference internal" href="#functions">函数</a><ul>
<li><a class="reference internal" href="#creating-sockets">创建套接字</a></li>
<li><a class="reference internal" href="#other-functions">其他功能</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#socket-objects">套接字对象</a></li>
<li><a class="reference internal" href="#notes-on-socket-timeouts">关于套接字超时的说明</a><ul>
<li><a class="reference internal" href="#timeouts-and-the-connect-method">超时与 <code class="docutils literal notranslate"><span class="pre">connect</span></code> 方法</a></li>
<li><a class="reference internal" href="#timeouts-and-the-accept-method">超时与 <code class="docutils literal notranslate"><span class="pre">accept</span></code> 方法</a></li>
</ul>
</li>
<li><a class="reference internal" href="#example">示例</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="asyncio-dev.html"
                        title="上一章">用 asyncio 开发</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="ssl.html"
                        title="下一章"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code> --- 套接字对象的TLS/SSL封装</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">提交 Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.7/Doc/library/socket.rst"
            rel="nofollow">显示源代码
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             >索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="ssl.html" title="ssl --- 套接字对象的TLS/SSL封装"
             >下一页</a> |</li>
        <li class="right" >
          <a href="asyncio-dev.html" title="用 asyncio 开发"
             >上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" >网络和进程间通信</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">版权所有</a> 2001-2020, Python Software Foundation.
    <br />
    Python 软件基金会是一个非盈利组织。
    <a href="https://www.python.org/psf/donations/">请捐助。</a>
    <br />
    最后更新于 6月 29, 2020.
    <a href="../bugs.html">发现了问题</a>？
    <br />
    使用<a href="http://sphinx.pocoo.org/">Sphinx</a>2.3.1 创建。
    </div>

  </body>
</html>